0

I use javascript prototypal inheritance where A "inherits" B. B uses defineProperty to define a setter for property prop. In A I want to override this behaviour:

Function.prototype.inherits = function (parent) 
{
    this.prototype              = Object.create(parent.prototype);
    this.prototype.constructor  = parent;
};

// --------------------------------------------
var B = function()
{
    this.myProp = 0;
};

Object.defineProperty(  B.prototype
                   ,    'prop'
                   ,    {
                        set:    function(val) 
                                {
                                    this.myProp = val;
                                }
                    });
// --------------------------------------------
var A = function(){};
A.inherits(B);

Object.defineProperty(  A.prototype
                   ,    'prop'
                   ,    {
                        set:    function(val) 
                                {
                                    // Do some custom code...

                                    // call base implementation
                                    B.prototype.prop = val; // Does not work!
                                }
                    });

// --------------------------------------------
var myObj = new A();
myObj.prop = 10;

Calling the base implementation does not work this way as the this pointer will be wrong. I would need to call something like B.prototype.prop.set.call(this, val); to fix it but this does not work.

Would be greatful about any ideas!

EDIT: As desired I added some more code.

Milad
  • 45
  • 7
  • @ "If so, why don't you just set prop to A as its own property?": Not sure if I understand this correctly. A and B are both "classes" with their methods/properties defined in the prototype. I need to be able to instantiate both. – Milad Feb 13 '15 at 17:16
  • Forget it, it appears, that I assumed totally different kind of code ; ). – Teemu Feb 13 '15 at 17:25
  • did you by any chance mean do the following: myObj .prop = 10 – Mike Atkins Feb 13 '15 at 17:53
  • Sure, thanks. Am I the only guy who has tried something like this? :) – Milad Feb 13 '15 at 18:13

1 Answers1

1

I believe you can use:

Object.getOwnPropertyDescriptor(B.prototype, 'prop').set.call(this, val);

http://jsbin.com/topaqe/1/edit