2016-08-08 40 views
0

ES是否說原型是所有物體的屬性?是的,「構造函數」和「對象實例」都是函數/對象,那麼它們都應該具有「原型」屬性。爲什麼我不能在JavaScript中使用對象的原型「isPrototypeOf」?

但當我:

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

_Instances_一般沒有'prototype's。只有構造函數纔有一個。你可以嘗試'Object.getPrototypeOf(o1)'。 'Array.prototype'與'[] .prototype'是一樣的。 – Xufox

回答

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)); 
+0

謝謝,但問題是,只要「Person()」創建了「o1」,那麼o1的原型是不是「Person.prototype」?爲什麼需要額外的原型分配? – Troskyvs

+0

啊,因爲原型在實例上不可用,但只在構造函數上可用。 –

相關問題