为什么函数原型被反复链接? [英] Why functions prototype is chained repeatedly?
问题描述
我是JavaScript的新手。我正在阅读JavaScript的好部分。它说:
I'm very new to JavaScript. I'm reading from JavaScript good parts. It says :
每个函数对象也是使用原型属性创建的
所以我做了类似的事情:
So I did something like this :
function test() {
}
console.log(test.prototype);
使用Chrome的开发者工具,我发现输出如下:
Using Chrome's developer tools, I find the output as follows :
我真的很担心这个输出。为什么构造函数
的原型
属性再次嵌套构造函数
?为什么这会像链一样继续?我在哪里错过这个概念?
I'm really confused with this output. Why does constructor
's prototype
property again nested with constructor
? And why does this goes on like a chain? Where I'm missing the concept?
提前致谢。
推荐答案
函数的 prototype
属性保存所有对象使用 new
运算符创建时,该函数的实例将继承。所有这些原型对象(通常)都有一个构造函数
属性,它指向函数 - 你有循环引用。因此,当 new test()
继承该属性时,(新测试).constructor === test
评估为 true
。
The prototype
property of a function holds the object from which all instances of that function will inherit when created with the new
operator. And all these prototype objects (usually) have a constructor
property which points back to the function - there you have the circular reference. So, as a new test()
inherits that property, (new test).constructor === test
evaluates to true
.
您需要区分原型
函数对象的属性和对象继承的原型对象 - 通常称为内部 [[prototype]]
属性。
You will need to distinguish between the prototype
property of a function object and the prototype object from which an object inherits - often referenced as "the internal [[prototype]]
property".
构造函数是一个函数,不是说函数
,而且两者都有。因此它继承自 Function.prototype
对象 - 其中构造函数
属性表示所有函数都由<$构造c $ c>函数构造函数。如果您的开发人员控制台将显示 Function
对象的原型,您可以看到它们。我认为设置中有一个选项。
A constructor is a function, not to say a Function
, and has both. Therefore it inherits from the Function.prototype
object - where the constructor
property says that all functions are constructed by the Function
constructor. If your developers console would show the prototype of Function
objects, you could see them. I think there is an option in the settings.
因此,着名的原型链不是关于构造函数
和/或 prototype
属性,但是关于该对象继承自的原型对象:
So, the famous "prototype chain" is not about the constructor
and/or prototype
properties, but about the prototype object from which that object inherits from:
function test() {} new test()
(a Function) (a test instance)
|| ||
|| ||
\/ \/
Function.prototype test.prototype
(a Function, by spec) (an Object)
|| ||
|| ||
\/ \/
Object.prototype Object.prototype
|| ||
|| ||
\/ \/
null null
这篇关于为什么函数原型被反复链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!