2017-03-28 4 views
0

私は同様の質問をしましたが、同じではありませんでした。これは、新しいES6クラスのキーワードと、これを処理する方法に焦点を当てています。 SignalRはクラスメソッドを呼び出しています。そのクラスメソッドの中で 'this'はクラスインスタンス自体ではなく、SignalRハブを参照します。 SignalRが新しいES6クラスを使用して呼び出すこのクラスメンバー内のクラスインスタンスを取得するにはどうすればよいですか?SignalRクラスのメソッドコールバックと 'this'

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(); 
     }); 
    } 
} 
+0

これはES6クラスとは何の関係もありませんが、それが働いたと全く同じ方法:あなたは矢印関数にするsayHelloを変換することができ、また

this.network.client.hello = this.sayHello.bind(gameLoad); 

:あなたは、その時点で、それまでgameLoadをバインドする必要があります。 ES5で。 – Bergi

答えて

1

クラスを使用する場合は、「this」が正しく設定されているように矢印関数を使用することをお勧めします。

あなたの例では、sayHelloをクライアントのhelloメソッドに割り当てます。

sayHello =() => { 
+0

これで、bind()を呼び出すと、その関数内で 'this'が利用できるようになります。私は矢印関数の構文の巨大なファンではありませんが、私はこれらを行っていきます。 – user441521

関連する問題