在向现有对象添加方法时,此关键字与对象名称

时间:2018-12-23 12:43:13

标签: javascript object methods constructor this

myFoo.becomeYounger = function(){
  this.age--;
};

让我们说我想向Foo的这个特定实例(而不是其他实例)添加一个方法。 我是否应该使用 this 关键字修改age属性

myFoo.becomeYounger = function(){
  myFoo.age--;
};

或者因为它已经存在,我应该用它的名字来引用它吗?

{{1}}

哪个更好/更快,还是有什么区别?

1 个答案:

答案 0 :(得分:0)

它们都可以工作,但是使用对象名称存在一些风险,请查看以下内容:

let user = {
  name: "John",
  age: 30,

  sayHi() {
    alert( user.name ); // leads to an error
  }

};


let admin = user;
user = null; // overwrite to make things obvious

admin.sayHi(); // Whoops! inside sayHi(), the old name is used! error!

通过使用this,该代码将可以正常工作,只需注意这种情况即可。

如果您想编写可重用的代码,则使用this更合适:

let user = { name: "John" };
let admin = { name: "Admin" };

function sayHi() {
  alert( this.name );
}

// use the same functions in two objects
user.f = sayHi;
admin.f = sayHi;

// these calls have different this
// "this" inside the function is the object "before the dot"
user.f(); // John  (this == user)
admin.f(); // Admin  (this == admin)

admin['f'](); // Admin (dot or square brackets access the method – doesn't matter)

要了解更多信息,请点击此处: https://javascript.info/object-methods