我知道javascript“类”与大多数语言完全不同,但是我想弄清楚为什么当我在构造函数中设置2个不同的值时,来自SignalR的回调为两个实例打印出20个。
class gameLoad{
constructor(value) {
this.value = value;
}
init(){
// create the network object and hook it's functions update
this.network = $.connection.testHub;
this.network.client.hello = this.sayHello.bind(this);
console.log(this.value);
}
// 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.value); //<--- this prints 20 2 times
}
create(){
var self = this;
// start the hub connection
$.connection.hub.start().done(function () {
console.log("Started!")
console.log("Calling server function.");
// make our first network call which will turn around and fire client.hello which is bound to this classes sayHello()
self.network.server.hello();
});
}
}
var game1 = new gameLoad(10);
game1.init();
game1.create();
var game2 = new gameLoad(20);
game2.init();
game2.create();