2016-02-06 47 views
2

,我讀了Object.gePrototypeOf(someObject)返回傳遞的對象和aPrototype.isPrototypeOf(someObject)返回true的原型如果aPrototypesomeObject原型。很明顯,如果Object.getPrototypeOf(someObject)返回一個名爲aPrototype的原型,那麼aPrototype.isPrototypeOf(someObject)將返回true。但是這不會發生在我的代碼中:Object.getPrototypeOf和example.isPrototypeOf(OBJ)給混亂的結果

function person(fname, lname) 
{ 
    this.fname = fname; 
    this.lname = lname; 
} 

var arun = new person('Arun', 'Jaiswal'); 

console.log(Object.getPrototypeOf(arun)); //person 
console.log(person.isPrototypeOf(arun)); //false 

怎麼了?

+0

@GameAlchemist:沒有。 'isPrototypeOf'同樣也測試整個鏈,'instanceof'的區別在於它不需要'.prototype'用來在鏈中查找的構造函數。 – Bergi

回答

3

作爲每MDN,的isPrototype語法是

prototypeObj.isPrototypeOf(obj) 

另外參閱isPrototypeOf vs instanceof

function person(fname, lname) 
 
{ 
 
    this.fname = fname; 
 
    this.lname = lname; 
 
} 
 

 
var arun = new person('Arun', 'Jaiswal'); 
 

 
console.log(Object.getPrototypeOf(arun)); //person 
 
console.log(person.prototype.isPrototypeOf(arun));

2

arun原型不是personperson.prototype

Object.getPrototypeOf(arun) === person.prototype; // true 
person.prototype.isPrototypeOf(arun); // true 
+0

那麼isPrototypeOf()的工作到底是什麼? –

1

isPrototypeOf不在構造函數本身上調用,而是在構造函數的prototype屬性上調用。

alert(person.prototype.isPrototypeOf(arun)); // true 

這意味着,阿倫的原型是不是person,但person.prototype