以下代码:
var cody = {
living:true,
age:23,
gender:'male',
getGender:function(){return cody.gender;}
};
与:
相同var cody = {
living:true,
age:23,
gender:'male',
getGender:function(){return this.gender;}
};
两个代码实现了相同的目标。唯一的区别是 cody 与关键字 this 的交换。在 Javascript 中使用关键字 this 有什么好处?它会提高性能吗?我们可以在 OOP 中忽略它吗?
最佳答案
this
指的是相关结构的当前实例化。例如,以下操作将失败:
var cody = {
living:true,
age:23,
gender:'male',
getGender:function(){return cody.gender}
};
var codyCopy = cody;
cody = "foobar";
//undefined
alert(codyCopy.getGender());
但是,使用 this
则不会,因为它正确引用了 codyCopy
:
var cody = {
living:true,
age:23,
gender:'male',
getGender:function(){return this.gender}
};
var codyCopy = cody;
cody = "foobar";
//male
alert(codyCopy.getGender());
关于javascript - 使用关键字 "this"有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36806358/