问题描述
我们知道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
.为什么Object
和Function
都具有相同的原型(最后结果)?
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继承:本机原型之间的原型链如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!