简体   繁体   中英

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.

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

You appear to be confused about how Object.defineProperty works. You only ever call defineProperty on Object , and you pass in the object you want to define a property of. So you don't need this magic, because defineProperty does not exist on instances of your class at all.

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 ). Then the setter/getter object. 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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