Javascript继承:本机原型之间的原型链如何工作 [英] Javascript inheritance : How prototype chain works between native prototypes

查看:78
本文介绍了Javascript继承:本机原型之间的原型链如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道Javascript中的所有内容都是从Object继承的:

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

前三个结果很有意义,因为obj继承自Rabbit函数,而函数本身继承自Function.但是,如果Function继承自Object,那么为什么第四个结果是False.为什么ObjectFunction都具有相同的原型(最后结果)?

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?

推荐答案

使用图像可以更好地解释此类问题(例如您所提出的问题):

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)

基本上,功能的__proto__链为:

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

这篇关于Javascript继承:本机原型之间的原型链如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆