覆盖例如如何在在公共职能
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