2016-08-19 6 views
-2
function test() { 
    this.a = { 
     b: 4 
    }; 
} 

test.prototype.a = { 
    c: 5 
}; 

var example = new test(); 

なぜexample.a.c == undefinedですか?Javascriptプロトタイプは継承されずに未定義ですか?

プロトタイプを継承して返さないでください。5


これが不可能な場合は、プロトタイプを返すようにコードを追加するにはいくつかの方法があります?:

function test() { 
    this.a = { 
     b: 4, 
     c: *this.return.prototype* 
    }; 
} 
+1

あなたのプロトタイプは 'this.a'がtest.prototype.a''よりも優先されることを除いて、example.a.c' 'のために働くだろう。 – Barmar

+0

@Barmarので、新しいオブジェクトを作成する2つのオブジェクトを持つ$ .extend()とは異なります。a = {b:4、c:5} ;? – seahorsepip

+1

正しいですが、プロトタイプは再帰的にマージされません。 – Barmar

答えて

1

はプロトタイプにアクセスa.cのgetterを定義します。

function test() { 
 
    this.a = { 
 
    b: 4, 
 
    get c() { 
 
     return test.prototype.a.c; 
 
    } 
 
    }; 
 
} 
 

 
test.prototype.a = { 
 
    c: 5 
 
}; 
 

 
var example = new test(); 
 
console.log(example.a.b); 
 
console.log(example.a.c); 
 
// update prototype 
 
test.prototype.a.c = 10; 
 
console.log(example.a.c);

-1

あなたが「A」を訪問したとき、それは最初に例に見つけます。見つからなければ、サンプル構造のプロトタイプで 'a'を見つけようとします。それでは、test.ptototype.c.に行きます。あなたのコードはexamlpe.c.を見つけることができません。このようにコードを変更できると思います。

function test() { 
    this.a = { 
     b: 4 
    }; 
} 
test.prototype.c = 5; 
var example = new test(); 
console.log(example.c);//print 5 
+1

彼は 'example.c 'ではなく' example.a.c'を望んでいます。 – Barmar

2

example.aいずれか一つのオブジェクトまたは他を参照するには、直接それが別のオブジェクトからプロパティを取得することはできません。

私は何だろうと、他の1から継承example.aオブジェクトを作っている:

function test() { 
 
    this.a = Object.create(test.a_proto); 
 
    this.a.b = 4; 
 
} 
 
test.a_proto = { 
 
    c: 5 
 
}; 
 
var example = new test(); 
 
console.log(example.a.b); // 4 (own) 
 
console.log(example.a.c); // 5 (inherited)

+0

この場合、 'example'を作成した後に' test.a_proto.c'を変更するとどうなりますか?継承されたプロトタイプを引き続き使用するか、 'Object.create(test.a_proto)'を呼び出すときにコピーを作成しましたか? – Barmar

+0

私はちょうどそれを試して、それはプロトから継承し続けます。ニース。 – Barmar

+0

@Barmarはい、 'test.a_proto'のプロパティの変更は継承されます。しかし、 'test.a_proto'自体を置き換えることはできません。 – Oriol

関連する問題