在下面的代码中,我有2个属性:
sharedProperty
:它有一个原始类型作为值,并且设置为只可配置。sharedMethodAsProperty
:它有一个值作为值,也可以设置为可配置。现在,在代码片段的末尾,我可以覆盖sharedProperty
就好了(readonly
和configurable
),但对于sharedMethodAsProperty
,我必须将其设置为writable
否则我抱怨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";
};
}());
答案 0 :(得分:1)
随着fuyushimoya的帮助,我意识到我是多么愚蠢,为什么它不起作用。
sharedProperty
已为man
对象重新定义,但永远不会为其分配新值,因此即使没有sharedProperty
为writable
,覆盖也会起作用。sharedMethodAsProperty
正在为man
对象分配一个新值。正在创建新的function
并将其分配给它。分配将要求它为writable
。使用Object.defineProperty()
重新定义它是有意义的,就像sharedProperty
对象覆盖man
的方式一样。