【发布时间】:2016-03-01 19:40:26
【问题描述】:
在 JS 构造函数中有些东西并不完全有意义。 当我做这样的事情时:
function extends(child, parent) {
child.prototype = Object.create(parent.prototype);
child.prototype.constructor = child;
};
永远不会调用“构造函数”。意思是,“child”函数确实被调用了,因为我们正在执行“new child()”。但如果我正在做这样的事情:
function extends(child, parent) {
child.prototype = Object.create(parent.prototype);
child.prototype.constructor = function() {
alert("test");};
};
“警报”永远不会触发,因为真正的“子”函数以任何方式被调用。
这是为什么呢?如何将构造函数重写为我想要的?
【问题讨论】:
-
只需将覆盖的
child传递给extends函数? -
在实例化
new child()时,将调用child构造函数。….prototype.constructordoesn't matter at all的值。
标签: javascript class oop constructor