在JavaScript中,我怎么知道哪个对象我不知道? 例如我怎样才能知道我继承了哪个对象
function a() {
this.c = 1;
}
function b() {
this.d = 2;
}
b.prototype = new a();
我该如何检查b继承?
谢谢。
在JavaScript中,我怎么知道哪个对象我不知道? 例如我怎样才能知道我继承了哪个对象
function a() {
this.c = 1;
}
function b() {
this.d = 2;
}
b.prototype = new a();
我该如何检查b继承?
谢谢。
//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
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
}
为什么当我做警报(x.constructor);其警报“函数a(){this.Cl = 1; }” 但是x.constructor == a是否工作? – user1801625
@ user1801625因为a是一个函数,它具有字符串表示形式'function a(){this.c = 1; }' –
谢谢我忘了你提醒我! – user1801625
的你可能想instanceOf。
if (b instanceOf a) {
console.log("b is instance a")
}
这也有走在整个原型链,所以如果它是一个父母,祖父母也没关系的优势,等
不错,不敢相信我忘了好旧的'instanceof' –