简体   繁体   中英

Why does `Array.length`, `Function.length`, `String.length`, etc return 1?

While teaching my JavaScript class yesterday, my students and I came across some interesting functionality that I thought might be worth capturing in a question and the answer I've come to.

Typing Array.length in the JS console in chrome returns 1 .

Likewise, Function.length returns 1 . This is important because:

Every function in JavaScript is actually a Function object. (MDN JS Ref: Function)

Thus, Object.length and likely all other native objects will and should return 1 as the value of the length property.

So, finally why is this behavior occurring?

Function.length itself is the answer:

Specifies the number of arguments expected by the function. MDN JS Ref: Function.length

When we write Function.length we are asking the Function constructor to tell us the number of formal, named parameters ("optional" - ie non-formal - parameters are accessed via the arguments property in the function body). Because the Function constructor expects exactly 1 formal named parameter, the result is 1 :

new Function ([arg1[, arg2[, ... argN]],] functionBody)

functionBody is the single formal named parameter. Therefore Function.length is 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM