【问题标题】:Why I cannot use an object's prototype in JavaScript "isPrototypeOf"?为什么我不能在 JavaScript "isPrototypeOf" 中使用对象的原型?
【发布时间】:2016-08-08 02:12:30
【问题描述】:

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”,那么我期望

Person.prototype == o2.prototype.prototype

但为什么还是失败了?

【问题讨论】:

  • Instances 通常没有prototypes。只有构造函数有一个。你可以试试Object.getPrototypeOf(o1)Array.prototype[].prototype 相同。

标签: javascript constructor prototype instance


【解决方案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));

【讨论】:

  • 谢谢,但问题是,只要“o1”是由“Person()”创建的,那么o1的原型是“Person.prototype”不是自动的吗?为什么需要额外的原型分配?
  • 啊,因为原型在实例上不可用,而只能在构造函数上。
猜你喜欢
  • 2017-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-28
  • 1970-01-01
相关资源
最近更新 更多