为什么NodeJS util.inherits函数中的“super_”属性添加到构造函数中?
我正在研究JavaScript中的一些不同的inheritance技术。 我一直在使用NodeJS util.inherits函数为我的最新项目。 我想知道:
- 为什么
super_
属性是在构造函数而不是原型上设置的? - 将它分配给超级构造函数的原型值不是更有意义吗? 由于构造函数总是可以从原型
constructor
属性中获取?
所以不是这样的:
constructor.super_ = superConstructor; constructor.prototype = Object.create(superConstructor.prototype, { constructor: { value: constructor, enumerable: false } });
这将是:
constructor.prototype = Object.create(superConstructor.prototype, { constructor: { value: constructor, enumerable: false }, super_:{ value: superConstructor.prototype, enumerable: false } });
这种方式调用超级函数是更容易,因为而不是:
this.constructor.super_.prototype.someFunction.call(this);
它会变成这样:
this.super_.someFunction.call(this);
这对我更有意义,但我很好奇,如果我失去了一些东西。 我也做了一个JSFiddle来展示这个实现。
预先感谢您的回复!