SignalR class 方法回调和 'this'
SignalR class method callback and 'this'
我有一个类似的问题,但不一样。这一篇着重于新的 ES6 class 关键字以及如何处理它。 SignalR 正在调用 class 方法。在 class 方法内部,'this' 指的是 SignalR 集线器而不是 class 实例本身。如何在 SignalR 使用新 ES6 classes 调用的 class 成员中获取 class 实例?
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 class 关键字以及如何处理它。 SignalR 正在调用 class 方法。在 class 方法内部,'this' 指的是 SignalR 集线器而不是 class 实例本身。如何在 SignalR 使用新 ES6 classes 调用的 class 成员中获取 class 实例?
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 = () => {