Troskyvs
Troskyvs

Reputation: 8047

How to make Javascript "isPrototypeOf" function return true?

I was trying this function to see if different objects have arelationship with each other, so I tried:

var o={name:'abc'};
var o2=o;
console.log(o.isPrototypeOf(o2));
console.log(o2.isPrototypeOf(o));

Well, it prints 2 falses. I felt weird that, "prototype" is a property/function of each function/object, so how does JS judge whether one object is the prototype of another?

I also tried:

var Person=function(){
    name='abc',
    age=30
};
var o1=new Person();
var o2=new Person();
console.log(o1.isPrototypeOf(o2));
console.log(o2.isPrototypeOf(o1));

Again, it prints 2 falses, while I expect 2 trues.

Upvotes: 1

Views: 98

Answers (2)

Maxx
Maxx

Reputation: 1748

After var o2=o o2 points to o. So o and o2 points to same object. Is o prototype of itself? No. Is o2 prototype of itself? No again.

In second part o1 is not a prototype of o2. Try to call

console.log(Person.prototype)

You will see the prototype object of instances of Person (it's not the prototype of Person function).

Also you can use obj.__proto__ to see prototype of obj. It's hidden property. Better not use it in production.

Upvotes: 0

slebetman
slebetman

Reputation: 113866

For an o to be a prototype of o2 the o2 object needs to be constructed from a constructor whose prototype is o. In other words, o2 needs to properly inherit o.

It is not enough that a variable is assigned an object or two objects are similar. One object must inherit from another.

So in the classic sense, this must happen:

var o = {};
var OConstructor = function () {};
OConstructor.prototype = o;

var o2 = new OConstructor();

o.isPrototypeOf(o2); // true

In modern code you can also inherit using Object.create():

var o = {};

var o2 = Object.create(o); 

o.isPrototypeOf(o2); // true

Upvotes: 1

Related Questions