Javascript inheritance : How prototype chain works between native prototypes

做~自己de王妃 提交于 2020-01-23 09:27:08

问题


As we know everything in Javascript inherits from Object:

So if I create an object using constructor function like below:

function Rabbit() {
  this.color = 'White'
}

let obj = new Rabbit();

alert(Rabbit.__proto__ === Function.prototype)       //true
alert(obj.__proto__ === Rabbit.prototype)            //true       
alert(obj.__proto__.__proto__ === Object.prototype)  //true

alert(Function.__proto__ === Object.prototype)  //false
alert(Object.getPrototypeOf(Function) === Object.getPrototypeOf(Object))  //true

The first 3 results make sense because obj inherits from Rabbit function which itself inherits from Function. But if Function inherits from Object then why is the 4th result False. Also why do both Object and Function have same prototype (last result)?

Can someone explain this behavior. Am i missing something here?


回答1:


Problems like this are better explained with images (like the one in your question):

Legend:

   blue color = objects
   {} = simple object (+constructor name)
   Ⓟ = prototype object (+constructor name)

   magenta color = functions (ƒ + function name)

Basically, the __proto__ chain for functions is:

concrete function (e.g. Rabbit, Object or Function itself) 
-> abstract function (aka Function.prototype) 
-> Object.prototype 
-> null 



回答2:


alert(Object.getPrototypeOf(Function) === Object.getPrototypeOf(Object)) // true

Both Function and Object are functions, their prototype is Function.prototype. Can be verified with

Object.getPrototypeOf(Function) === Function.prototype // true
Object.getPrototypeOf(Object) === Function.prototype // true

This very object was used to create the prototype of Function function, thus

Function.__proto__ === Function.prototype // true

rather than

Function.__proto__ === Object.prototype // false

alert(Object.getPrototypeOf(Function) === Function.prototype)
alert(Object.getPrototypeOf(Object) === Function.prototype)
alert(Function.__proto__ === Function.prototype)



回答3:


You’re confusing Function.__proto__ (and equivalently Object.getPrototypeOf(Function)), the prototype of the function constructor, with Function.prototype.__proto__, the prototype of functions.

function Rabbit() {
  this.color = 'White'
}

let obj = new Rabbit();

console.log(Rabbit.__proto__ === Function.prototype)       //true
console.log(obj.__proto__ === Rabbit.prototype)            //true       
console.log(obj.__proto__.__proto__ === Object.prototype)  //true

console.log(Function.prototype.__proto__ === Object.prototype)  //true
console.log(Object.getPrototypeOf(Function.prototype) === Object.getPrototypeOf(Object.prototype))  //false


来源:https://stackoverflow.com/questions/58464218/javascript-inheritance-how-prototype-chain-works-between-native-prototypes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!