为什么我不能在 JavaScript "isPrototypeOf" 中使用对象的原型?
Why I cannot use an object's prototype in JavaScript "isPrototypeOf"?
ES说prototype是所有对象的属性吗?是的,"constructor function"和"object instance"都是function/object,那么它们应该都有"prototype"属性.
但是当我尝试时:
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 没有这样的 property/method?
然后我试了这个:
console.log(o2.prototype.prototype.isPrototypeOf);
也失败了,说
console.log(o2.prototype.prototype.isPrototypeOf);
^
TypeError: Cannot read property 'prototype' of undefined
这就更奇怪了:如果o2的原型是"Person",那么我预计
Person.prototype == o2.prototype.prototype
但是为什么还是失败了?
你应该使用:
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));
ES说prototype是所有对象的属性吗?是的,"constructor function"和"object instance"都是function/object,那么它们应该都有"prototype"属性.
但是当我尝试时:
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 没有这样的 property/method?
然后我试了这个:
console.log(o2.prototype.prototype.isPrototypeOf);
也失败了,说
console.log(o2.prototype.prototype.isPrototypeOf);
^
TypeError: Cannot read property 'prototype' of undefined
这就更奇怪了:如果o2的原型是"Person",那么我预计
Person.prototype == o2.prototype.prototype
但是为什么还是失败了?
你应该使用:
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));