0

Crockford が推奨する継承と混同しています。Crockford メソッドと一般的な (既定の) 方法の主な違いは何ですか。

//Crockford method
      function object(o) {
            function F() {}
            F.prototype = o;
            return new F();
        }

以下はより一般的な方法です

function Base(name) {
    this.name = name;
}

Base.prototype.getName = function () {
    return 'Base :' + this.name;
}

function Child(name) {
    this.name = name;
}

Child.prototype.getName = function () {
    return 'Child :' + this.name;
}

function Kid(name) {
    this.name = name;
}

Kid.prototype.getName = function () {
    return 'Kid :' + this.name;
}

Child.prototype = new Base ("childBase");
Kid.prototype = new Child ("kidChild");

var base = new Base ("myBase");
var child = new Child("myChild");
var kid = new Kid("myKid");

console.log(base.getName());
console.log(child.getName());
console.log(kid.getName());

上記の2つの違いは何ですか?

実は私はクロックフォード法を完全には理解できていません。一般的な方法の欠点とクロックフォード法の利点を理解するのに役立つ人はいますか。

4

1 に答える 1

1
Child.prototype = new Base ("childBase");
Kid.prototype = new Child ("K1", "K2");

これらの行で、独自の名前を持つ 2 つのオブジェクトをインスタンス化します。それは何の役に立つのですか?より複雑な環境では、これによりアプリケーションが壊れる可能性さえあります。Baseコンストラクターがプライベート変数と特権メソッドを使用すると、そのすべての子が同じインスタンスで同じ変数を共有します!

したがって、通常はこの方法を使用するべきではありませんが、古いバージョンのObject.createである Crockfords 関数を使用してください。で呼び出されBase.prototype、このオブジェクトから直接継承する新しいオブジェクトを作成します。プロトタイプ チェーンを設定するだけで、コンストラクタ コードは実行しません。Crockford の Object.create shimを理解すると、詳細を理解するのに役立ちます。作成されたオブジェクトは、Children のプロトタイプ オブジェクトとして最適です。この回答もお読みください。

于 2012-08-05T01:56:27.760 に答える