重写继承的原型方法并在新的方法中调用原始方法

时间:2013-07-25 12:55:23

标签: javascript inheritance override prototype

在以下代码中,如何访问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'原型链“。这样的事情可能吗?

1 个答案:

答案 0 :(得分:5)

您可以使用Object.getPrototypeOf

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

注意:Object.getPrototypeOf是ECMASript 5,请参阅compatibility


还有非标准和已弃用的__proto__属性compatibility

  

引用与其内部[[Prototype]]

相同的对象

并允许您像这样调用A s'日志方法

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

但是

  

首选方法是使用Object.getPrototypeOf。

相关问题