【发布时间】:2012-05-10 06:12:53
【问题描述】:
我有一个实现继承的函数:
inherit = function(base) {
var child = function() { console.log('Crappy constructor.'); };
child.prototype = new base;
child.prototype.constructor = child;
return child;
}
我想我可以这样使用它:
var NewClass = inherit(BaseClass);
NewClass.prototype.constructor = function() {
console.log('Awesome constructor.');
}
但是当我像这样创建 NewClass 的新实例时:
var instance = new NewClass();
我收到消息 Crappy constructor. 正在打印到控制台。为什么构造函数不被覆盖?以及如何覆盖它?
【问题讨论】:
-
对象继承自其构造函数的原型,而不是它们自己的。将方法添加到
BaseClass.prototype以查看差异。
标签: javascript inheritance constructor