在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' –