[英]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.