javascript - Function、Array 和 Object 构造函数的 length 属性是什么?

标签 javascript oop semantics

函数、数组和对象构造函数的长度静态属性是什么?

静态方法是有道理的,但是长度静态属性呢?

Object.getOwnPropertyNames(Array)
["length", "name", "arguments", "caller", "prototype", "isArray"]

Object.getOwnPropertyNames(Function)
["length", "name", "arguments", "caller", "prototype"]

注意:我得到的是 Function.prototype 的 length 属性的答案,这里没有问到。

Object.getOwnPropertyNames(Function.prototype)
["length", "name", "arguments", "caller", "constructor", "bind", "toString", "call", "apply"]

Object.getOwnPropertyNames(Object)
["length", "name", "arguments", "caller", "prototype", "keys", "create", "defineProperty", "defineProperties", "freeze", "getPrototypeOf", "getOwnPropertyDescriptor", "getOwnPropertyNames", "is", "isExtensible", "isFrozen", "isSealed", "preventExtensions", "seal"]

最佳答案

ArrayFunctionObject都是构造器,所以都是函数。函数的 length 属性指定函数采用的(命名)参数的数量。来自 ECMA-262 第 3 版,第 15 节:

Every built-in Function object described in this section—whether as a constructor, an ordinary function, or both—has a length property whose value is an integer. Unless otherwise specified, this value is equal to the largest number of named arguments shown in the section headings for the function description, including optional parameters.

正如 DCoder 指出的那样:

ECMA-262 3rd edition, sections 15.2.3, 15.3.3 and 15.4.3 specify that all these constructors have a length property, whose value is 1.

关于静态字段的观点:在 JavaScript 中没有静态字段这样的东西,因为在 JavaScript 中没有类。只有原始值、对象和函数。对象和函数(它们的行为也像对象一样)具有属性

一件可能令人困惑的事情是 Function 实际上是一个函数。一个鲜为人知的事实是您可以使用此构造函数创建函数。例如:

var identity = new Function("a", "b", "return a")
console.log(identity(42))

以上将打印42。现在注意两件事:Function 实际上接受参数并用它们做一些事情;我向 Function 构造函数传递了多个参数,即使 Function.length 等于 1。结果 identity 也是一个函数,其 length 属性设置为值 2,因为它是一个有两个参数的函数。

关于javascript - Function、Array 和 Object 构造函数的 length 属性是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14050709/

相关文章:

javascript - 动态 columnWidth 在 Masonry 中导致堆叠图像

c++ - 如何在类中将 bool 值更改为字符串?

javascript - 如何在 JavaScript 中为 namespace 中的对象创建静态成员?

html - 如何为 WCAG 2.0 Compliance 标记按钮?

php - 用 php 或 css 隐藏元素?

java - 谁能解释一下为什么这段代码返回 false

javascript - 谷歌图表 API : more than one label rows on x axis?

php - 使用 AJAX 返回表中的所有记录

javascript - 如何通过函数的参数在 javascript 函数中触发 javascript 函数?

C# 虚拟方法