我有一个 Person
构造函数,方法是 sayHello
var Person = function(firstName,lastName) {
this.lastName = lastName;
this.sayHello = function() {
return "Hi there " + firstName;
}
};
然后我在 Person
的原型(prototype)上定义了一个不同版本的 sayHello 方法:
Object.defineProperties(Person.prototype,{
sayHello: {
value: function() {
return 'Hi there';
},
enumerable: true
}
});
现在,如果我创建一个 Person 实例并对其调用 sayHello - 我注意到它使用的是在原型(prototype)上定义的 sayHello 版本。
var JoeBlow = new Person('Joe','Blow');
> JoeBlow.sayHello()
< "Hi there" // I was expecting "Hi there Joe"
这让我感到困惑。
为什么 JoeBlow 对象不使用 它自己的 sayHello 实现,而是在其原型(prototype)对象上查找 sayHello?
最佳答案
默认情况下,使用 defineProperties
定义的属性是只读的。
参见 MDN
writable
true if and only if the value associated with the property may be changed with an assignment operator.
Defaults to false.
不幸的是,当您尝试在旧式 JS 中设置只读属性时,它会默默地失败而不是抛出异常,因此这真的很难调试。
如果您在 strict mode 中运行过它你会得到:
TypeError: Cannot assign to read only property 'sayHello' of [object Object]
您可以显式定义该属性为可写。
Object.defineProperties(Person.prototype,{
sayHello: {
value: function() {
return 'Hi there';
},
enumerable: true,
writable: true
}
});
然后 this.sayHello = function() {
不会静默失败,您将成功屏蔽原型(prototype)上的属性版本。
关于javascript - 原型(prototype)上的属性会覆盖实际对象的属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33872013/