ES是否说原型是所有物体的属性?是的,“构造函数”和“对象实例”都是函数/对象,那么它们都应该具有“原型”属性。
但是当我尝试时:
var Person=function(){
this.name='abc';
this.age=30;
};
var o1=new Person();
var o2=new Person();
console.log(o2.prototype.isPrototypeOf(o1));
控制台打印一个例外说明:
console.log(o2.prototype.isPrototypeOf(o1));
^
TypeError: Cannot read property 'isPrototypeOf' of undefined
那是什么错误?我知道
console.log(Person.prototype.isPrototypeOf(o1));
的工作原理。但是为什么“Person”有isPrototypeOf方法的原型,而o2没有这样的属性/方法?
然后我尝试了这个:
console.log(o2.prototype.prototype.isPrototypeOf);
它也失败了,说
console.log(o2.prototype.prototype.isPrototypeOf);
^
TypeError: Cannot read property 'prototype' of undefined
这更奇怪:如果o2的原型是“人物”,那么我希望
Person.prototype == o2.prototype.prototype
但为什么它仍然失败?
答案 0 :(得分:1)
您应该使用:
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));