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 chain
的constructor chain
。
因为通常我隐藏在分离的文件和prototype
文件夹下的protected
private
方法。 只有public
方法与constructor
函数在same scope
。 此外,让他们很容易在不同的class级移动。 所有这些都被命名为prototype.method = function() {...}
,所以他们大多只能访问原型对象。
或者,如果知道通过constructor chain
任何好处,我们将不胜感激。 这就是为什么我find这个职位。