如何防止在 javascript 中执行 getter setter 继承属性的方法
How to prevent the execution of getter setter methods of inherited properties in javascript
场景一:
//create a parent object
var parent = {}
// define a property prop1 on parent
parent.prop1 = 'value1'
parent.prop1 // will print 'value1'
// create a child object with parent as the prototype
var child = Object.create(parent)
child.prop1 // will print "value1"
// create prop1 on child
child.prop1 = 'value updated'
child.prop1 // will print 'value updated'
parent.prop1 // will print "value1"
此处 child
上的 prop1
将隐藏(或覆盖)parent
上的 prop1
场景二:
// define parent
var parent = {}
//define setter/getters for prop1
Object.defineProperty(parent, 'prop1',
{
get: function () {
console.log('inside getter of prop1');
return this._prop1;
},
set: function (val) {
console.log('inside setter of prop1');
this._prop1 = val;
}
});
// define prop1 on parent
parent.prop1 = 'value1' // prints: inside setter of prop1
//access prop1
parent.prop1 // prints inside getter of prop1 and "value1"
// create a new object with parent as the prototype
var child = Object.create(parent)
// access prop1
child.prop1 // inside getter of prop1 "value1"
// update prop1 on child
child.prop1 = 'updated value'// inside setter of prop1
在最后一步,就像在 场景 1 中一样,我希望 child
上的 prop1
覆盖 prop1
上定义的 prop1
18=].
如何实现?
正如@dandavis 所建议的,re-defining child 上的 属性 覆盖了 parent 的 属性。
Object.defineProperty(child, "prop1", {value: 'updated value'});
场景一:
//create a parent object
var parent = {}
// define a property prop1 on parent
parent.prop1 = 'value1'
parent.prop1 // will print 'value1'
// create a child object with parent as the prototype
var child = Object.create(parent)
child.prop1 // will print "value1"
// create prop1 on child
child.prop1 = 'value updated'
child.prop1 // will print 'value updated'
parent.prop1 // will print "value1"
此处 child
上的 prop1
将隐藏(或覆盖)parent
prop1
场景二:
// define parent
var parent = {}
//define setter/getters for prop1
Object.defineProperty(parent, 'prop1',
{
get: function () {
console.log('inside getter of prop1');
return this._prop1;
},
set: function (val) {
console.log('inside setter of prop1');
this._prop1 = val;
}
});
// define prop1 on parent
parent.prop1 = 'value1' // prints: inside setter of prop1
//access prop1
parent.prop1 // prints inside getter of prop1 and "value1"
// create a new object with parent as the prototype
var child = Object.create(parent)
// access prop1
child.prop1 // inside getter of prop1 "value1"
// update prop1 on child
child.prop1 = 'updated value'// inside setter of prop1
在最后一步,就像在 场景 1 中一样,我希望 child
上的 prop1
覆盖 prop1
上定义的 prop1
18=].
如何实现?
正如@dandavis 所建议的,re-defining child 上的 属性 覆盖了 parent 的 属性。
Object.defineProperty(child, "prop1", {value: 'updated value'});