4

私はJavascriptでOOPの基本を学んでいて、私が通常見ているものとは異なる継承の例に出くわしました。

典型的な:

ChildClass.prototype = new ParentClass();

別の方法:

function clone(object) {
  function OneShotConstructor(){}
  OneShotConstructor.prototype = object;
  return new OneShotConstructor();
}

SecondClass.prototype = clone(FirstClass.prototype);

プロトタイプが別のオブジェクトであるオブジェクトを作成するときに、なぜ後者が好まれるのでしょうか。

4

1 に答える 1

3

継承しようとしているカスタムタイプ(別名クラス)のコンストラクターを呼び出すためです。そして、それは副作用があるかもしれません。次のことを想像してみてください。

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
于 2012-11-26T19:07:25.477 に答える