Reputation: 1223
In javascript how can I know which object I inehrit? for example
function a() {
this.c = 1;
}
function b() {
this.d = 2;
}
b.prototype = new a();
How can I check that b inherit from a?
Thank you.
Upvotes: 2
Views: 68
Reputation: 1630
of you probably want instanceOf.
if (b instanceOf a) {
console.log("b is instance a")
}
This also has the advantage of walking the whole prototype chain so it does not matter if it is a parent, grandparent, etc
Upvotes: 0
Reputation: 179246
Use the 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
Upvotes: 2
Reputation: 58619
Use the constructor property of b.prototype
or any instance of 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
}
Upvotes: 1
Reputation: 21840
Try this
b.prototype.constructor.name
Working example: http://jsfiddle.net/psrcK/
Upvotes: 1