简体   繁体   中英

Function.length is not the same as this.length. Why?

Here's the simple function that expects three agruments. It is possible to get the expected number of arguments either via arguments.callee.length or myFunc.length . Why this.length returns 0? Shouldn't this and myFunc refer to the same function object? I'm a bit confused :).

function myFunc(a, b, c){
   console.log(arguments.callee.length, myFunc.length, this.length);
}

myFunc("a","b"); //=> prints 3 3 0

A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode. In most cases, the value of this is determined by how a function is called. It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind method to set the value of a function's this regardless of how it's called, and ECMAScript 2015 introduced arrow functions whose this is lexically scoped (it is set to the this value of the enclosing execution context).[ Ref ]

In your scenario: this belongs to owner of the function we are executing or to the object we are invoking a method of. (how a function is called)

In your example, owner of myFunc is window ( window.myFunc("a","b"); ) hence this.length == 0 . If you open window object in console, you will find length property which is having value as 0 .


To have your own this argument while invoking the function , Use .call , The call() method calls a function with a given this value and arguments provided individually.

 function myFunc(a, b, c) { console.log(arguments.callee.length, myFunc.length, this.length); } myFunc.call(myFunc, "a", "b"); //=> prints 3 3 3 
 <script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script> 

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