javascript - JavaScript 中的函数是对象吗?

标签 javascript

函数是 JavaScript 中的“函数”对象吗?如果是这样,当我创建一个构造函数时,例如:

//this is a constructor function

function foo(){
    this.name="xx";
}

foo 是否有一个名为 proto 的属性,指向该函数的原型(prototype)?我怎样才能看到这个属性?

ps:如果通过new关键字创建实例时创建了proto,为什么function foo没有它呢?根据上面的内容,foo是通过new Function创建的。

最佳答案

is function a object in javascript?

是的。

Does foo has a property named proto pointing to the Function 's prototype?

未命名proto,不。这是一个有点令人困惑的区域:

  • 所有对象都有一个它们继承的底层原型(prototype)对象。从 ES5 开始,您可以通过 Object.getPrototypeOf 获取对该对象的引用(例如,var p = Object.getPrototypeOf(blah) 为您提供对 blah 的原型(prototype))。 一些引擎(包括 Firefox 的 SpiderMonkey)还通过伪属性 __proto__ 提供底层原型(prototype),这将是 in the spec as of ES6 ,但官方only when JavaScript is used in browsers .

  • 另外,所有普通函数都有一个名为 prototype 的属性,它不是该函数的底层原型(prototype)(见上文)。相反,该对象将被分配为通过 new 关键字使用该函数作为构造函数创建的对象的底层原型(prototype)。

既然这有点困惑,我们画一张图吧。假设我们有这样的代码:

function Foo() {
    this.name = "xx";
}

var f = new Foo();

(因为我将它用作构造函数,所以我使用名称 Foo 而不是 foo 来遵守约定。)

这是我们现在内存中的内容:

+------------+
|  Function  |
| (function) |
+------------+       +-----------+
| __proto__  |----+->| (object)  | This is the object assigned to functions
| prototype  |----/  +-----------+ as their underyling prototype
+------------+    |  | call      |
                  |  | apply     |
                  |  | bind      |
                  |  | ...       |
                  |  +-----------+
+------------+    |
|     Foo    |    |
| (function) |    |
+------------+    |
| __proto__  |----+
|            |          +----------+
| prototype  |----+---->| (object) | This is the object assigned to
+------------+    |     +----------+ objects created via `new Foo`
                  |     | (blank)  |
                  |     +----------+
+-----------+     |
|     f     |     |
| (object)  |     |
+-----------+     |
| __proto__ |-----+
| name: xx  |
+-----------+

(I've left off the references to Object.property above to keep things simpler.)

How can I see this property.

See above, either __proto__ (on only some engines for now, will be standard in ES6) or via Object.getPrototypeOf (ES5).

Example:

// Shows you the object referenced by Function.prototype,
// which is `foo`'s underyling prototype
// ONLY WORKS ON SOME ENGINES for now (including Firefox's SpiderMonkey)
console.log(foo.__proto__);

// Shows you the object referenced by foo.prototype
console.log(foo.prototype);

关于javascript - JavaScript 中的函数是对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28339346/

相关文章:

javascript - 如何判断复选框是否被选中?

javascript - !!变量和变量有什​​么区别

javascript - 使用 em 统一居中内容

javascript - jQuery onClick 执行

提交表单时在浏览器中显示的 JavaScript 代码,而不是脚本的结果

javascript - 如何修复 TypeError : Cannot read property 'authenticate' of undefined passportjs

javascript - 如果字符串比数字长,不要写

javascript - Google platform.js 有时不会触发 onload 回调

javascript - 避免 jQuery(预)加载图像

javascript - 使用类模型/ typescript 时检索属性指令中的参数值?