2012-11-15 106 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") 
} 

这也有走在整个原型链,所以如果它是一个父母,祖父母也没关系的优势,等

相关问题