19

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();

結果は次のとおりです。

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

しかし、私が欲しいのは:

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

私は何が欠けていますか?

4

2 に答える 2

39

探しているものを実現する方法は次のとおりです。

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

  console.log('my new name is: ' + this.name);
};

これにより、thisコンテキストが、私が想定しているのではBなく、のインスタンスであることが保証されB.super_.prototypeます。

于 2013-02-22T00:08:07.097 に答える