2

javascriptでは、どのオブジェクトが継承されているかをどのように知ることができますか? 例えば

function a() {
    this.c = 1;
}

function b() {
    this.d = 2;
}
b.prototype = new a();​

b が a から継承されていることを確認するにはどうすればよいですか?

ありがとうございました。

4

4 に答える 4

2

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
于 2012-11-15T23:21:30.937 に答える
1

これを試して

 b.prototype.constructor.name

実例: http: //jsfiddle.net/psrcK/

于 2012-11-15T23:18:09.040 に答える
1

のコンストラクター プロパティ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
}
于 2012-11-15T23:20:06.590 に答える
0

おそらくinstanceOfが必要です。

if (b instanceOf a) {
    console.log("b is instance a")
}

これには、プロトタイプチェーン全体をウォークするという利点もあるため、親、祖父母などは関係ありません。

于 2012-11-15T23:25:08.893 に答える