【问题标题】:util.inherits - how to call method of super on instance?util.inherits - 如何在实例上调用 super 的方法?
【发布时间】:2013-02-21 23:19:49
【问题描述】:

我正在使用 util.inherits method from node.js 并且似乎无法获得所需的行为。

var util = require("util");

function A() {
  this.name = 'old';
}

A.prototype.log =  function(){
  console.log('my old name is: '+ this.name);
};

function B(){
  A.call(this);
  this.name = 'new';
}

util.inherits(B, A);

B.prototype.log = function(){
  B.super_.prototype.log();
  console.log('my new name is: ' + this.name);
}

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

结果是:

my old name is: undefined 
my new name is: new

但是我想要的是:

my old name is: new 
my new name is: new

我错过了什么?

【问题讨论】:

    标签: node.js inheritance


    【解决方案1】:

    以下是实现您想要的目标的方法:

    B.prototype.log = function () {
      B.super_.prototype.log.apply(this);
    
      console.log('my new name is: ' + this.name);
    };
    

    这确保this 上下文是B 的实例,而不是B.super_.prototype 我想。

    【讨论】:

    • 其他方式:B.super_.prototype.log.call(this);
    • 顺便说一句,电话是更好的选择..jsperf.com/function-calls-direct-vs-apply-vs-call-vs-bind/6
    • 我更喜欢使用this关键字:this.constructor.super_.prototype.log.call(this),这样你就不需要在方法中再次使用类名了
    • @kit 使用 this 关键字确实有效,但有一个副作用。示例:C 继承 B 继承 A 并且它们都有 log 函数。 this.constructor.super_ 将始终返回 B。因此,如果B 想要调用A 中的函数并使用this.constructor.super_.prototype.log.call(this)B 只会调用它自己。
    • 直接使用prototype怎么样? Object.getPrototypeOf(prototype).log.call(this),这样就不用找super_了。
    【解决方案2】:

    我更喜欢通过prototype chain而不是constructor chain调用super的方法,如下所示。

    var prototype = C.prototype;
    
    prototype.log = function() {
      Object.getPrototypeOf(prototype).log.call(this)
    
      // or old style
      prototype.__proto__.log.call(this)
    }
    

    他们都在访问超类的原型对象,但是使用prototype chain可能比constructor chain中的constructor.super_.prototype更好。

    因为通常我将protectedprivate 方法隐藏在单独的文件中和prototype 文件夹下。只有public 方法与same scope 中的constructor 函数一起使用。此外,为了让他们轻松地在不同的班级之间移动。它们都被命名为prototype.method = function() {...},所以大部分只能访问原型对象。

    或者如果知道通过constructor chain 有什么好处会很感激?这就是我找到这篇文章的原因。

    【讨论】:

      猜你喜欢
      • 2021-12-02
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 2018-05-27
      • 2012-11-02
      • 2012-08-09
      • 1970-01-01
      相关资源
      最近更新 更多