问题描述
JavaScript函数的原型链中的函数在哪里?
Where is Function in the prototype chain of a JavaScript function?
工作示例:在Chrome的控制台中,我创建了以下函数:
Working Example: In Chrome's console, I created the following function:
> var f = function() { alert(1); }
调用 f()
正确结果使用以下控制台声明检查该功能时的一个警告:
invocation with f()
correctly results an an alert of the number 1. Upon examination of the function with the following console statement:
> console.dir(f)
注意原型如何以key / /的形式列为Object值对 prototype:Object
,表示函数 f
直接从Object继承。很公平; JavaScript中的数组和其他实体也从Object继承。
Notice how the prototype is listed as Object, in the form of key/value pair prototype: Object
, meaning that function f
inherits directly from Object. Fair enough; arrays and other entities in JavaScript also inherit from Object.
冲突来自以下观察。输入以下命令:
The conflict results from the following observation. Enter the following command:
f instanceof Function
这导致 true
。
据我所知,用户-created函数继承自Function对象,而Function对象又继承自Object;但是,对于我的生活,我通过检查f的原型链找不到它。
As I understand it, user-created functions inherit from the Function object, which in turn inherits from Object; however, for the life of me, I can't find it by inspecting the prototype chain for f.
哪里是功能
在函数f的原型链中?
Where is Function
in the prototype chain for function f?
tyvm
推荐答案
函数
本身不是,它是 Function.prototype
。它应该在下面函数 f
:
Function
itself is not, it's the Function.prototype
. It should be right "below" the function f
:
f
|
v
Function.prototype
|
v
Object.prototype
|
v
null
您看到的是。原型
f
的属性,是函数自己的原型对象 - 假设 f
将是一个构造函数,然后所有新f
实例将继承自 f.prototype
。
What you see as the .prototype
property of f
, is the function's own prototype object - assume f
would be a constructor, then all new f
instances would inherit from f.prototype
.
不。公共 .prototype
属性不得与内部原型链混淆(通常表示为 [[prototype]] 内部属性。您可以使用 Object.getPrototypeOf
访问原型链。有关详细信息,请访问,也许或。
Nope. The public .prototype
property must not be confused with the internal prototype chain (usually denoted as [[prototype]] internal property). You can access the prototype chain with Object.getPrototypeOf
. More information about that at __proto__ VS. prototype in JavaScript, maybe Why functions prototype is chained repeatedly? or http://eloquentjavascript.net/chapter8.html.
这篇关于JavaScript函数原型:对象,函数还是两者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!