Javascript 为什么我用两个不同的“值”得到相同的值;“实例”;
我知道javascript“类”与大多数语言并不完全一样,但我正试图弄清楚,当我在它们的构造函数中设置了2个不同的值时,为什么我从SignalR发出的回调为这两个实例打印了20个Javascript 为什么我用两个不同的“值”得到相同的值;“实例”;,javascript,signalr,Javascript,Signalr,我知道javascript“类”与大多数语言并不完全一样,但我正试图弄清楚,当我在它们的构造函数中设置了2个不同的值时,为什么我从SignalR发出的回调为这两个实例打印了20个 class gameLoad{ constructor(value) { this.value = value; } init(){ // create the network ob
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();
类游戏加载{
构造函数(值){
这个值=值;
}
init(){
//创建网络对象并钩住它的函数更新
this.network=$.connection.testHub;
this.network.client.hello=this.sayHello.bind(this);
console.log(this.value);
}
//这是从信号器调用的,“this”现在指的是此函数中的信号器中心。如何获取类实例?
你好{
console.log(this.value);//20被打印两次,因为它在构造函数中打印一次,第二次是在调用init()时。我的意思是,它在末尾打印两次。我得到10打印两次,然后20打印两次,然后“开始!调用服务器函数”打印两次,然后20打印两次。它从signer调用返回,signer正在调用绑定到sayHello的hello。服务器集线器函数和客户端函数的名称相同。啊,我想我知道发生了什么。到client.hello的第二个绑定需要时间。由于是异步的,对服务器的调用需要更长的时间因此,当它准备返回到客户端并启动javascript函数时,存在的绑定是20实例绑定。因为它没有添加多个钩子,只是1。嗯,我想知道是否可以为回调获取多个钩子。