在下面的代码中我有 2 个属性:
sharedProperty
:它具有原始类型作为值,并且被设置为仅可配置。sharedMethodAsProperty
:它有一个函数作为值,并且也被设置为可配置。
现在,在片段末尾附近,我可以很好地覆盖 sharedProperty
(它是 readonly
和 configurable
),但是对于 sharedMethodAsProperty
我必须将其设置为可写
,否则我会收到关于readonly
属性无法被覆盖的提示。有想法吗?
(function () {
'use strict';
var Person = function () {
Object.defineProperties(Person.prototype, {
"sharedProperty" : {
value : 10,
configurable: true
},
"sharedPropertyThroughAccessor" : {
get : function() {
return "shared property";
},
configurable: true
},
"sharedMethodAsProperty" : {
value: function() {
return "shared method as property";
},
configurable: true,
// if we omit this true here, we can't override it below.
//writable: true
}
});
};
Object.prototype.sharedMethod = function() {
return "shared method";
};
var person1 = new Person("John", "Doe");
var man = Object.create(person1);
var sharedProperty = Object.getOwnPropertyDescriptor(Person.prototype, "sharedProperty").value;
Object.defineProperty(man, "sharedProperty", {
value : 11 + sharedProperty,
configurable: true
});
var sharedPropertyThroughAccessor = Object.getOwnPropertyDescriptor(Person.prototype, "sharedPropertyThroughAccessor");
// bind with man, else you'd get person1's properties
var sharedFn = sharedPropertyThroughAccessor.get.bind(man);
Object.defineProperty(man, "sharedPropertyThroughAccessor", {
get : function() {
return sharedFn() + " overridden";
}
});
var sharedMethodFn = person1.sharedMethod.bind(man);
// can't do: man.prototype. That property only exists on functions.
man.sharedMethod = function() {
return sharedMethodFn() + " overridden";
};
var sharedMethodAsProperty = Object.getOwnPropertyDescriptor(Person.prototype, "sharedMethodAsProperty");
var sharedMethodAsPropertyFn = sharedMethodAsProperty.value.bind(man);
man.sharedMethodAsProperty = function() {
return sharedMethodAsPropertyFn() + " overridden";
};
}());
最佳答案
在 fuyushimoya 的帮助下,我意识到自己是多么愚蠢以及为什么它不起作用。
sharedProperty
是为man
对象重新定义的,它永远不会被分配新值,这就是为什么即使sharedProperty
没有被重写也能工作的原因>可写
。sharedMethodAsProperty
正在为man
对象分配新值。正在创建一个新的函数
并将其分配给它。赋值要求它可写
。使用Object.defineProperty()
重新定义它是有意义的,就像sharedProperty
被man
对象覆盖一样。
关于javascript - 除非设置为可写,否则无法覆盖 readOnly 可配置函数值对象原型(prototype)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31204113/