简体   繁体   English

在Javascript中重新定义Object.defineProperty

[英]Redefine Object.defineProperty in Javascript

I would like to learn if it is possible to redefine the "definePropery" function of the Object(.prototype) in a subclass(.prototype) so that the setter not only sets the value of the property but also eg executes an additional method. 我想学习是否有可能在子类(.prototype)中重新定义Object(.prototype)的“ definePropery”函数,以便设置器不仅设置属性的值,而且例如执行其他方法。

I have tried something like that: 我已经尝试过类似的方法:

Myclass.prototype.defineProperty = function (obj, prop, meth) {
    Object.defineProperty.call(this, obj, prop, {
        get: function () {
            return obj[prop]
        },
        set: function () {
            obj[prop] = n;
            alert("dev")
        }
    })
}

But id does not work 但是ID不起作用

You appear to be confused about how Object.defineProperty works. 您似乎对Object.defineProperty工作方式感到困惑。 You only ever call defineProperty on Object , and you pass in the object you want to define a property of. 永远只能调用definePropertyObject ,并在你所要定义的属性的对象传递。 So you don't need this magic, because defineProperty does not exist on instances of your class at all. 因此,您不需要这种魔术,因为defineProperty在类的实例上根本不存在。

var obj = {a:123};

Object.defineProperty(obj, 'foo');
// works fine!

obj.defineProperty('foo');
// TypeError: Object #<Object> has no method 'defineProperty'

But that means you can add that in, no problem: 但这意味着您可以添加它,没问题:

Myclass.prototype.defineProperty = function (obj, prop, meth) {
    Object.defineProperty(this, prop, {
        get: function () {
            return obj[prop]
        },
        set: function (n) {
            obj[prop] = n;
            alert("dev")
        }
    })
}

Note this line: 注意这一行:

Object.defineProperty(this, prop, {

We pass in the object we want the property on ( this ), and the name of the property ( prop ). 我们传入需要属性的对象( this )和属性名称( prop )。 Then the setter/getter object. 然后是setter / getter对象。 No need to override anything at all. 根本不需要覆盖任何内容。 You are simple providing a method that allow an object to declare it's own properties. 您只需提供一种允许对象声明其自身属性的方法即可。

See working example here: http://jsfiddle.net/TeZ82/ 在这里查看工作示例: http : //jsfiddle.net/TeZ82/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM