util.inherits - 如何在实例上调用super方法?

p11*_*00i 19 inheritance node.js

我正在使用util.inherits 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();
Run Code Online (Sandbox Code Playgroud)

结果是:

my old name is: undefined 
my new name is: new
Run Code Online (Sandbox Code Playgroud)

不过我想要的是:

my old name is: new 
my new name is: new
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Pas*_*cle 38

以下是如何实现您的目标:

B.prototype.log = function () {
  B.super_.prototype.log.apply(this);

  console.log('my new name is: ' + this.name);
};
Run Code Online (Sandbox Code Playgroud)

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

  • 其他方式:B.super_.prototype.log.call(this); (8认同)
  • 我更喜欢使用`this`关键字:`this.constructor.super_.prototype.log.call(this)`,这样你就不需要在方法中再次使用类名 (2认同)