javascriptでは、どのオブジェクトが継承されているかをどのように知ることができますか? 例えば
function a() {
this.c = 1;
}
function b() {
this.d = 2;
}
b.prototype = new a();
b が a から継承されていることを確認するにはどうすればよいですか?
ありがとうございました。
javascriptでは、どのオブジェクトが継承されているかをどのように知ることができますか? 例えば
function a() {
this.c = 1;
}
function b() {
this.d = 2;
}
b.prototype = new a();
b が a から継承されていることを確認するにはどうすればよいですか?
ありがとうございました。
instanceof
演算子を使用します:
//capital letters indicate function should be used as a constructor
function A() {...}
function B() {...}
B.prototype = new A();
var a,
b;
a = new A();
b = new B();
console.log(a instanceof A); //true
console.log(a instanceof B); //false
console.log(b instanceof A); //true
console.log(b instanceof B); //true
console.log(B.prototype instanceof A); //true
のコンストラクター プロパティb.prototype
または の任意のインスタンスを使用しますb
。
function a(){
this.c=1;
}
function b(){
this.d=2;
}
b.prototype=new a();
x = new b()
if(x.constructor == a){
// x (instance of b) is inherited from a
}
おそらくinstanceOfが必要です。
if (b instanceOf a) {
console.log("b is instance a")
}
これには、プロトタイプチェーン全体をウォークするという利点もあるため、親、祖父母などは関係ありません。