util.inherits – 如何调用超级实例的方法?

我正在玩node.js util.inherits 方法,似乎无法得到所需的行为。

 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 

我错过了什么?

以下是如何实现你正在寻找的东西:

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

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

我更喜欢通过prototype chain而不是像以下这样的constructor chain来调用超类的方法。

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

他们都在访问超类的原型对象,但是使用prototype chain可能比constructor chainconstructor chain

因为通常我隐藏在分离的文件和prototype文件夹下的protected private方法。 只有public方法与constructor函数在same scope 。 此外,让他们很容易在不同的class级移动。 所有这些都被命名为prototype.method = function() {...} ,所以他们大多只能访问原型对象。

或者,如果知道通过constructor chain任何好处,我们将不胜感激。 这就是为什么我find这个职位。