【问题标题】:Overriding inherited prototype method and calling the original one inside the new one覆盖继承的原型方法并在新方法中调用原始方法
【发布时间】:2013-07-25 12:55:23
【问题描述】:

在下面这段代码中,如何访问B.prototype.log 内部的A.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' ”。这样的事情可能吗?

【问题讨论】:

  • 实际上,A.prototype.log.call(this) 正是我搜索的内容。谢谢!

标签: javascript inheritance overriding prototype


【解决方案1】:

你可以使用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]] 相同的对象

并允许您像这样调用As 的日志方法

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

但是

首选方法是使用 Object.getPrototypeOf。

【讨论】:

  • @C5H8NNaO4 代码中有一个类型,正确的是Object.getPrototypeOf ( B.prototype.log) .call(this)
猜你喜欢
  • 1970-01-01
  • 2010-09-22
  • 2013-08-15
  • 1970-01-01
  • 2014-10-06
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多