因为您将调用您尝试继承的自定义类型(又名类)的构造函数。这可能会产生副作用。想象一下:
var instancesOfParentClass = 0;
function ParentClass (options) {
instancesOfParentClass++;
this.options = options;
}
function ChildClass () {}
ChildClass.prototype = new ParentClass();
您的计数器已增加,但您并没有真正创建有用的 ParentClass 实例。
另一个问题是所有实例属性(请参阅this.options
参考资料)都将出现在 ChildClass 的原型上,而您可能不希望这样。
注意:使用构造函数时,您可能有实例属性和共享属性。例如:
function Email (subject, body) {
// instance properties
this.subject = subject;
this.body = body;
}
Email.prototype.send = function () {
// do some AJAX to send email
};
// create instances of Email
emailBob = new Email("Sup? Bob", "Bob, you are awesome!");
emailJohn = new Email("Where's my money?", "John, you owe me one billion dollars!");
// each of the objects (instances of Email) has its own subject
emailBob.subject // "Sup? Bob"
emailJohn.subject // "Where's my money?"
// but the method `send` is shared across instances
emailBob.send === emailJohn.send // true