6

在下面的代码中,我如何访问A.prototype.log内部B.prototype.log

function A() {}

A.prototype.log = function () {
    console.log("A");
};

function B() {}

B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;

B.prototype.log = function () {
    //call A.prototype.log here
    console.log("B");
};

var b = new B();
b.log();

我知道我可以写A.prototype.log.call(this),但我想也许有一种更优雅的方式,可以让我以相对的方式调用它,比如“调用原型链中下一个更高实例的方法'log'”。这样的事情可能吗?

4

1 回答 1

5

You could use Object.getPrototypeOf

...
B.prototype.log = function () {
    Object.getPrototypeOf (B.prototype).log.call(this)
    console.log("B");
};
...
b.log(); //A B

Note: Object.getPrototypeOf is ECMASript 5, see the compatibility


There is also the non standard and deprecated __proto__ property (compatibility) which

references the same object as its internal [[Prototype]]

and would allow you to call your As' log method like this

B.prototype.__proto__.log.call(this)

But

the preferred method is to use Object.getPrototypeOf.

于 2013-07-25T13:00:12.813 回答