Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 信号器类方法回调和“this”_Javascript_Signalr_Es6 Class - Fatal编程技术网

Javascript 信号器类方法回调和“this”

Javascript 信号器类方法回调和“this”,javascript,signalr,es6-class,Javascript,Signalr,Es6 Class,我有一个类似的问题,但不一样。本文重点介绍新的ES6类关键字以及如何处理它。信号器正在调用一个类方法。在该类方法中,“this”指的是信号器集线器,而不是类实例本身。如何在Signal使用新ES6类调用的这个类成员中获取类实例 class gameLoad { constructor(){ } init(){ // create the network object and hook it's functions update for loading

我有一个类似的问题,但不一样。本文重点介绍新的ES6类关键字以及如何处理它。信号器正在调用一个类方法。在该类方法中,“this”指的是信号器集线器,而不是类实例本身。如何在Signal使用新ES6类调用的这个类成员中获取类实例

class gameLoad {
    constructor(){

    }

    init(){
        // create the network object and hook it's functions update for loading
        this.network = $.connection.testHub;
        this.network.client.hello = this.sayHello;
    }

    // this is called from signalR and 'this' now refers to the signalR hub inside this function. how can I get the class instance?
    sayHello(){
        console.log(this);    // 'this' refers to signalR object not gameLoad object
    }

    create(){
        var self = this;
        $.connection.hub.start().done(function () {
            console.log("Started!")
            console.log("Calling server function.");

            // make our first network call which will turn around and call client.hello which is bound to this classes sayHello() member function
            self.network.server.hello();
        });
    }
}

使用类时,最好使用箭头函数,以便正确设置“this”

在您的示例中,您将sayHello分配给客户机的hello方法。此时您需要将gameLoad绑定到它:

this.network.client.hello = this.sayHello.bind(gameLoad);
或者,您可以将sayHello转换为箭头函数:

sayHello = () => {

这与ES6类无关,它在ES5中的工作方式完全相同。那么调用bind将使该函数中的“This”可用吗?我不太喜欢箭头函数语法,但我会尝试一下。