简体   繁体   中英

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). Should I use this keyword to modify the age property

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.

Also if you like to do reusable code, using this fits better:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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