简体   繁体   中英

Why I cannot use an object's prototype in JavaScript “isPrototypeOf”?

Does ES say that prototype is a property of all objects? Is yes, both "constructor function" and "object instance" are all function/object, then they should all have "prototype" property.

But when I tried:

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

The console prints an exception saying:

console.log(o2.prototype.isPrototypeOf(o1));
                    ^
TypeError: Cannot read property 'isPrototypeOf' of undefined

What is that error? I know that

console.log(Person.prototype.isPrototypeOf(o1));

works. But why "Person" has prototype with isPrototypeOf method, while o2 failed to have such property/method?

Then I tried this:

console.log(o2.prototype.prototype.isPrototypeOf);

It also fails, saying

console.log(o2.prototype.prototype.isPrototypeOf);
                        ^
TypeError: Cannot read property 'prototype' of undefined

This is even more weird: if o2's prototype is "Person", then I expect

Person.prototype == o2.prototype.prototype

But why does it still fail?

You should use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM