2015-10-27 57 views
0

假設我有一個類,有一些方法需要從該類的私有函數中訪問。像這樣:從私有函數訪問類成員

var A = function() 
{ 
    this.a = 0; 

    var f = function(){ // Private function 
     this.a; // Undefined 
    }; 

    f(); 
}; 

什麼是更好的方法來做到這一點?我試圖把它傳遞給函數,但如果我必須爲許多函數執行它,這是不實際的。

var A = function() 
{ 
    this.a = 0; 

    var f = function(self){ 
     self.a; 
    }; 

    f(this); 
}; 

有沒有更好的方式來做到這一點?或者設計是否存在根本性缺陷,我應該考慮其他選擇?謝謝!

+2

另外,請請注意,下一行約定*上的大括號在JavaScript *中不能很好地工作,並可能導致一些常見的陷阱和陷阱。 –

回答

1

爲什麼是的,用ES6,我們得到了箭頭函數,用自動this綁定!

var A = function() { 
    this.a = 0; 

    var f =() => { // Private function 
     console.log(this.a); // Woohoo! 
    }; 

    // If only one statement, can be shortened to 
    // var f =() => console.log(this.a); 

    f(); 
}; 

對於不那麼幸運:.bind()同樣存在:

var A = function() { 
    this.a = 0; 

    var f = function() { // Private function 
     console.log(this.a); // Woohoo! 
    }.bind(this); // this inside the function is bound to the passed this. 

    // If only one statement, can be shortened to 
    // var f =() => console.log(this.a); 

    f(); 
}; 
+0

這看起來非常好,不幸的是它不適用於我正在使用的環境中:( – SlySherZ

+0

@SlySherZ:已編輯。 –

1

爲了避免 '本' 的困惑我見過一個共同的模式如下:

var A = function() { 
    var self = this; 
    self.a = 0; 

    var f = function(){ // Private function 
     self.a; // Defined 
    }; 

    f(); 
};