javascript - 使用关键字 "this"有什么好处?

标签 javascript

以下代码:

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/

相关文章:

javascript - iCheck 库 : value of selected radio button

javascript - 尝试并捕获 promise

javascript - jQuery offsetparent 也返回非定位父级

javascript - 无法让我的 Javascript 添加或删除类

javascript - 如何继承EventTarget对象?

javascript - Meteor:在模板内渲染模板

Javascript 正则表达式特殊字符

javascript - jsPlumb:如何在 "mouseup"事件完成后获取元素

javascript - 我的 Jquery 无法识别变量值是怎么回事

javascript - 同时监听多个按键事件