1

プロトタイプの継承がどのように機能するか、およびインタープリターがプロトタイプチェーンを移動してプロパティを見つける方法については、多くのことを読みました。

function Man()
{
    this.hands=2;//1
}
function father()
{
    this.name="";
}
father.prototype= new Man();//2

var malay= new father();
var abhik= new father();

ここで私の質問は、文 #1 と #2 が呼び出されるのは 1 回のみということです。「abhik」と「malay」は両方とも同じ Man オブジェクトを共有する必要がありますか? したがって、メモリには 3 つのオブジェクトがあります。1.abhik 2.malay 3.man (両方で共有される 1 つのインスタンス) したがって、そのロジックによって、変更された値はオブジェクト間で共有される必要がありますか?

malay.hands=3;
console.log(abhik.hands);
abhik.hands=4;
console.log(malay.hands);

しかし、そうではありません。なんでそうなの ?

4

2 に答える 2

2

3 つのオブジェクトがあり、両方が同じインスタンスabhikからmalay継承されているという理解は正しいです。Manしかし、およびオブジェクトに新しいhandsプロパティを設定すると、それらに独自のプロパティが与えられ、プロトタイプからプロパティを継承しなくなります。malayabhikhandshandsMan

図:

最初に と を作成malayした後abhikの 3 つのオブジェクトのモックは次のとおりです。

father.prototype -> {hands: 2} 
malay -> {name: ""}   // Empty name property, NO hands property
abhik -> {name: ""}   // Empty name property, NO hands property

またはのhandsプロパティをチェックすると、インタープリターはそのようなプロパティがないことを確認し、プロトタイプ チェーンをチェックして、親にプロパティがあることを検出します。したがって、インタープリターはその値を報告します。malayabhikfather.prototypehands2

プロパティを設定するhandsと、オブジェクトは次のようになります。

father.prototype -> {hands: 2} 
malay -> {name: "", hands: 3}   // Empty name property, OWN hands property
abhik -> {name: "", hands: 4}   // Empty name property, OWN hands property

これで、オブジェクトはすべて独自のhandsプロパティを持ちます。

リソース:これは、javascript の継承に関する非常によく書かれた (しかし長い) 記事です: http://manuel.kiessling.net/2012/03/23/object-orientation-and-inheritance-in-javascript-a-comprehensive-説明/

于 2013-05-23T04:55:14.063 に答える