0

我使用 javascript 原型继承,其中 A “继承” B. B 用于defineProperty为 property 定义 setter prop。在 AI 中想要覆盖这种行为:

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;

以这种方式调用基本实现不起作用,因为this指针将是错误的。我需要打电话B.prototype.prop.set.call(this, val);来修复它,但这不起作用。

对任何想法都会很感激!

编辑:根据需要,我添加了更多代码。

4

1 回答 1

1

我相信你可以使用:

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

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

于 2015-02-13T19:43:24.433 回答