2017-05-28 99 views
0

如何從嵌套函數引用類變量/方法?

class Foo { 
 
    constructor() { 
 
    this.foobar = "foobar"; 
 
    } 
 
    bar() { 
 
    let _this = this; 
 
    return function() { 
 
     try { 
 
     alert("Attempt 1: "+foobar);//ReferenceError: foobar is not defined 
 
     myMethod(); 
 
     } catch(err) {console.log(err);} 
 
     try { 
 
     alert("Attempt 2: "+this.foobar);//TypeError: this is undefined 
 
     this.myMethod(); 
 
     } catch(err) {console.log(err);} 
 
     try{ 
 
     alert("Attempt 3: "+_this.foobar);//Works! 
 
     _this.myMethod(); 
 
     } catch(err) {console.log(err);} 
 
    }(); 
 
    } 
 
    myMethod() { 
 
    alert("myMethod()"); 
 
    } 
 
} 
 
new Foo().bar();

上面的例子是非常簡單的 - 裏面bar()匿名函數是一個jQuery的呼叫最初,但問題的緣故,我沒有包括。

爲什麼不嘗試1和2的工作?我是否必須使用_this技巧來引用類變量/方法? 如何從嵌套函數引用類變量/方法?

回答

0

您是否熟悉this關鍵字在JavaScript中的工作原理?它的價值取決於函數的調用方式,而不是如何定義。例如,如果你做到以下幾點:

var dog = { 
 
    greeting:"woof", 
 
    talk:function(){ 
 
    console.log(this.greeting); 
 
    } 
 
}; 
 

 
var cat={ 
 
    greeting:"meow", 
 
    talk:dog.talk 
 
}; 
 

 
dog.talk(); 
 
cat.talk();

你會看到,當通話功能被稱爲對象的方法,該對象將被用作this值。

ES6類也是如此,其中類方法仍然是JavaScript函數,用於決定this值的規則仍然適用。如果你想避免聲明的附配的變量,你應該考慮使用bind

var mammal = { 
 
    greeting:"<noise>", 
 
    getTalk:function(){ 
 
    return function(){ 
 
     console.log(this.greeting); 
 
    }; 
 
    }, 
 
    getTalkBinded:function(){ 
 
    return (function(){ 
 
     console.log(this.greeting) 
 
    }).bind(this); 
 
    } 
 
}; 
 

 
var dog={ 
 
    greeting:"woof", 
 
    talk:mammal.getTalk(), 
 
    talkBinded:mammal.getTalkBinded() 
 
}; 
 

 
var cat={ 
 
    greeting:"meow", 
 
    talk:mammal.getTalk(), 
 
    talkBinded:mammal.getTalkBinded() 
 
}; 
 

 
dog.talk(); 
 
cat.talk(); 
 
dog.talkBinded(); 
 
cat.talkBinded();

0

您正在返回自執行功能的執行結果和函數執行this其全球範圍內的期間(不你的類對象)。使其工作使用() => {}()箭頭函數調用語法,因爲它捕獲當前上下文,或function() { }.bind(this)()

0

看到這個簡單的例子,

function a(){ 
    this.someProp = 5; 
    console.log(this); 

    var _this = this; //so we explicitly store the value of `this` to use in a nested function 

    return function(){ 
     //value of `this` will change inside this function 
     this.anotherProp = 6; 
     console.log(this); 

     //to use the methods and props of original function use `_this` 
     console.log(_this) 
    } 
} 

var c = a.call({}) //prints {someProp: 5} 
c.call({}) //prints {anotherProps: 6} {someProp: 5}