[英]How do I access a private variable in a public function that is overridden in the public function
例如
var MyClass = function(){
var that = this;
var my_var = "I want this";
var another_var = "this one is easy";
this.aPublicFunc = function(my_var){
console.log(my_var); // logs "I don't want this";
console.log(another_var); // logs "this one is easy";
console.log(this.my_var); // logs undefined which makes sense as the this context is the context of the calling function.
console.log(that.my_var); // logs undefined
};
};
var an_object = new MyClass();
var an_object.aPublicFunc("I don't want this");
不要覆蓋它。 它使代碼的可讀性和混亂性降低。
像my_var
一樣的私有變量只能在構造函數中的代碼及其范圍內定義的函數(如aPublicFunc()
)進行訪問。 並且,要訪問它們,您必須使用對它們的常規javascript引用。 當您使用相同的名稱定義aPublicFunc()
的參數時,您將隱藏該外部作用域變量,並且無法按定義方式訪問它。 這些私有變量不是對象的成員,而是在閉包中捕獲的變量。 在javascript中,在閉包中訪問變量的唯一方法是從該閉包范圍內的代碼開始,並且只有在沒有任何內容覆蓋其名稱的情況下,您才能訪問它們。
您的簡單解決方案是將參數名稱或局部變量更改為稍有不同的名稱。 如果您確實希望它們看起來相似,則可以在其中一個前面加上下划線,如下所示:
var MyClass = function(){
var that = this;
var _my_var = "I want this";
var _another_var = "this one is easy";
this.aPublicFunc = function(my_var){
console.log(_my_var); // logs "I want this";
console.log(_another_var); // logs "this one is easy";
console.log(my_var); // logs "I don't want this"
};
};
var an_object = new MyClass();
var an_object.aPublicFunc("I don't want this");
或像下面這樣使參數更明顯:
var MyClass = function(){
var that = this;
var my_var = "I want this";
var another_var = "this one is easy";
this.aPublicFunc = function(new_my_var){
console.log(my_var); // logs "I want this";
console.log(another_var); // logs "this one is easy";
console.log(new_my_var); // logs "I don't want this"
};
};
var an_object = new MyClass();
var an_object.aPublicFunc("I don't want this");
您可以在這里看到這最后一個作品: http : //jsfiddle.net/jfriend00/Jeaaz/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.