[英]“this” returning undefined, after function call
當我調用一個函數時,“ this”包含所有“ stuff”,但是當我調用一個調用另一個函數的函數時,“ this”在第二個函數內部返回未定義。
碼:
class test { test() { console.log(this) // => returns class functions ect.. this.run(this.test2); } run(func){ func() } test2() { console.log(this) // => returns undefined this.function3(); // => ERROR } function3() { console.log("hey") } } var t = new test(); t.test();
為什么代碼會表現為這種方式? 以及如何解決這個問題
啊,那些都是關閉的。 上下文( this
)將有所不同,具體取決於從哪個上下文調用該函數。 對於javascript,函數是對象,並且與類對象的綁定是week。 可以將其與類分離,並與on問題分開使用。 這就是為什么當您調用this.someFunc()
它僅提供一個函數,而不提供此實際實例的函數。 繞過它的最常見方法是將對象上下文保存到單獨的變量中,而不是使用this
。 像這樣:
class test {
var self = this;
test() {
console.log(self)
this.run(self.test2);
}
run(func){
func();
}
test2() {
console.log(self);
self.function3();
}
function3() {
console.log("hey");
}
}
當傳遞給函數的run
被執行,它的this
指向一個新的執行上下文,而不是你所希望的類的實例。
可以通過將其執行上下文綁定到該類的實例來“解決”(傳遞給run
,例如
this.run(this.test2.bind(this))
或者我是構造函數,例如
constructor () {
this.test2 = this.test2.bind(this)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.