0

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

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
kwicher
  • 2,092
  • 1
  • 19
  • 28

1 Answers1

3

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/

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • It seems that I did miss a point about the Object.defineProperty method. What I really thought is that defineProperty is called behind the scenes every time the new property is defined for the objects. If so what I meant to do is to reopen "Object" class and redefine the method. – kwicher Nov 07 '13 at 19:30
  • 1
    `defineProperty` is _not_ called when you create a property. You call `Object.defineProperty` to create a property of an object with custom behavior. You can get callbacks with [Harmony Proxies](http://soft.vub.ac.be/~tvcutsem/proxies/) but I believe support for them is somewhat uncommon at the moment. – Alex Wayne Nov 07 '13 at 20:24