Javascript 除非设置为“可写”,否则无法重写易于配置的函数值对象原型属性
在下面的代码中,我有两个属性:Javascript 除非设置为“可写”,否则无法重写易于配置的函数值对象原型属性,javascript,oop,inheritance,prototype,Javascript,Oop,Inheritance,Prototype,在下面的代码中,我有两个属性: sharedProperty:它有一个原语类型作为值,并被设置为仅可配置 sharedMethodAsProperty:它有一个作为值的函数,并且也被设置为可配置 现在,在代码片段的末尾,我可以覆盖sharedProperty很好(它是readonly和configurable),但是对于sharedMethodAsProperty,我必须将其设置为writable,否则我会收到无法覆盖readonly属性的投诉。想法 (function () { 'use
:它有一个原语类型作为值,并被设置为仅可配置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";
};
}());
在fuyushimoya的帮助下,我意识到自己有多笨,为什么它不起作用
是为sharedProperty
对象重新定义的,它从未被赋予新的值,这就是为什么即使man
不可写,覆盖也可以工作的原因sharedProperty
正在为sharedMethodAsProperty
对象分配一个新值。正在创建一个新的man
,并分配给它。赋值要求它是可写的。使用函数
重新定义它是有意义的,就像Object.defineProperty()
对象如何重写man
一样sharedProperty
sharedProperty
是可写的?@fuyushimoya无处可写。它不是可写的,只是可配置的。我没有提到它是可写的,是吗?只有sharedMethodAsProperty
需要是可写的。