【问题标题】:How to prevent the execution of getter setter methods of inherited properties in javascript如何防止在javascript中执行继承属性的getter setter方法
【发布时间】:2015-03-22 05:58:28
【问题描述】:

场景 1:

//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

场景 2:

// 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

在最后一步,就像在 scenario1 中一样,我希望 child 上的 prop1 覆盖 parent 上定义的 prop1

如何做到这一点?

【问题讨论】:

  • 由于我们没有在child上定义prop1,所以delete语句没有作用。
  • Object.defineProperty(child, "prop1", {value: 'updated value'});
  • @dandavis,非常感谢。那行得通。

标签: javascript angularjs object prototype


【解决方案1】:

正如@dandavis 建议的那样,重新定义子级的属性会覆盖父级的属性。

Object.defineProperty(child, "prop1", {value: 'updated value'});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2014-06-17
    • 1970-01-01
    • 2019-05-04
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多