2017-07-23 19 views
1

我已經看到幾個關於在類和函數中使用「this」的問題,但我不認爲我已經看到我在找什麼特定。第三方庫綁定回調,但我需要訪問類屬性

我的情況是:

我打電話從第三方庫中的函數在一個類的方法。但是,第三方庫函數正在調用callback.bind(this),我需要訪問它綁定的上下文。

但我也希望能夠訪問類屬性。這可能嗎? 如果不是,有什麼潛在的解決方法?代碼大綱看起來是這樣的:

class MyClass { 
    myProperty = 'something'; 

    myMethod() { 
    console.log(this.myProperty); 
    } 

    otherMethod() { 
    thirdPartyLibrary.functionRequiringCallback(function() { 
     this.MyMethod(); //undefined 
     this.requiredThirdPartyFunction(); //"this" refers to thirdPartyLibrary 
    }); 
    } 
} 

我當然可以做出回調箭頭功能,因此,「這」指的是類範圍的,但我不會有機會獲得「requiredThirdPartyFunction」。

任何幫助,將不勝感激。

回答

3

當您想要參考您的實例this時,您始終可以使用舊的that = this分配。您將this分配給作用域中的變量(通常爲that),然後您可以在回調中引用它。

otherMethod() { 
    const that = this; // set a reference to the instance this 

    thirdPartyLibrary.functionRequiringCallback(function() { 
    that.MyMethod(); // that refers to your class instance this 
    this.requiredThirdPartyFunction(); //"this" refers to thirdPartyLibrary 
    }); 
} 

另一個選擇是結合myMethod,通過使用箭頭功能或功能#結合,然後結合的方法分配給一個變量:

class MyClass { 
    myProperty = 'something'; 

    myMethod =() => console.log(this.myProperty); 

    otherMethod() { 
    const myMethod = this.myMethod; // assign the bound method to a variable 

    thirdPartyLibrary.functionRequiringCallback(function() { 
     MyMethod(); // will be invoked with original this 
     this.requiredThirdPartyFunction(); //"this" refers to thirdPartyLibrary 
    }); 
    } 
} 
+0

哇,這是爲我做的。這意味着我的問題基本上是所有其他類似問題的重複......謝謝澄清! – ZenPylon

1

有沒有這麼多的選擇在這裏。由於只有一個this,它可以是詞彙:

otherMethod() { 
    thirdPartyLibrary.functionRequiringCallback(() => { 
     this.MyMethod(); 
     thirdPartyLibrary.requiredThirdPartyFunction(); 
    }); 
    } 

或動態:

otherMethod() { 
    const _this = this; 
    thirdPartyLibrary.functionRequiringCallback(function() { 
     _this.MyMethod(); 
     this.requiredThirdPartyFunction(); 
    }); 
    } 

第一個選項是更具可讀性和可能是一個更好的選擇,因爲它不是從代碼明顯在回調之內this === thirdPartyLibrary以上。