簡體   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);

可以說我想向該Foo的特定實例添加一個方法(而不是其他實例)。 我是否應該使用關鍵字來修改age屬性

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

還是應該以其名稱引用該對象,因為它已經存在?

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

哪一個更好/更快,或者有什么區別?

它們都可以工作,但是使用對象名稱存在一些風險,請查看以下內容:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM