覆蓋例如如何在在公共職能
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'? – deceze 2012-02-02 12:18:44
答案是:你沒有。更好地命名你的變量和函數參數。 – 2012-02-02 12:21:12
'my_var'和'another_var'是你的例子中的全局變量。全局變量和局部變量不是神奇地成爲你創建的對象的屬性,所以'that.my_var'不能工作,除非你明確地指定它。在你的例子中,當調用'an_object.aPublicFunc(...)''this'時也指'that'。 – 2012-02-02 12:21:56