简体   繁体   English

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

[英]this keyword vs object name when adding method to existing object

function Foo(name, age){
  this.name = name;
  this.age = age;
  this.announce = function(){
    alert(this.name + " is " + this.age + " years old");
  };
}

var myFoo = new Foo("John", 42);

Lets say I want to add a method to this particular instance of Foo (not to the others). 可以说我想向该Foo的特定实例添加一个方法(而不是其他实例)。 Should I use this keyword to modify the age property 我是否应该使用关键字来修改age属性

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

or should I refer to the object by its name since it already exists? 还是应该以其名称引用该对象,因为它已经存在?

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

Which one is better/faster or is there any difference whatsoever? 哪一个更好/更快,或者有什么区别?

They both work, but there are some risks about using the object name, look at this: 它们都可以工作,但是使用对象名称存在一些风险,请查看以下内容:

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!

By using this , the code would worked correctly, just take care about this kind of scenarios. 通过使用this ,代码可以正常工作,只需注意这种情况即可。

Also if you like to do reusable code, using this fits better: 另外,如果您想编写可重用的代码,则使用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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM