2012-11-15 109 views

回答

2

使用instanceof operator

//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 
+0

不錯,不敢相信我忘了好舊的'instanceof' –

1

使用的b.prototype constructor屬性或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 
} 
+0

爲什麼當我做警報(x.constructor);其警報「函數a(){this.Cl = 1; }」 但是x.constructor == a是否工作? – user1801625

+0

@ user1801625因爲a是一個函數,它具有字符串表示形式'function a(){this.c = 1; }' –

+0

謝謝我忘了你提醒我! – user1801625

0

的你可能想instanceOf

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

這也有走在整個原型鏈,所以如果它是一個父母,祖父母也沒關係的優勢,等

相關問題