Object.getPrototypeOf 和 example.isPrototypeOf(obj) 给出了令人困惑的结

Object.getPrototypeOf and example.isPrototypeOf(obj) gave confusing results

本文关键字:example getPrototypeOf isPrototypeOf obj Object      更新时间:2023-09-26

我读到Object.gePrototypeOf(someObject)返回传递对象的原型,如果aPrototypesomeObject的原型,则aPrototype.isPrototypeOf(someObject)返回true。对我来说很明显,如果Object.getPrototypeOf(someObject)返回一个名为 aPrototype 的原型,那么aPrototype.isPrototypeOf(someObject)将返回 true。但它在我的代码中没有发生:

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

怎么了?

根据 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));

arun的原型不是person而是person.prototype

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

isPrototypeOf不是在构造函数本身上调用,而是在构造函数的原型属性上调用。

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

这意味着阿伦的原型不是person,而是person.prototype