継承しようとしているカスタムタイプ(別名クラス)のコンストラクターを呼び出すためです。そして、それは副作用があるかもしれません。次のことを想像してみてください。
var instancesOfParentClass = 0;
function ParentClass (options) {
instancesOfParentClass++;
this.options = options;
}
function ChildClass () {}
ChildClass.prototype = new ParentClass();
カウンターはインクリメントされていますが、ParentClassの有用なインスタンスを実際には作成していません。
もう1つの問題は、すべてのインスタンスプロパティ(を参照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