Home > Article > Web Front-end > Javascript Study Notes - Functions (4): arguments object_basic knowledge
Every Javascript function can access a special variable in its own scope - arguments. This variable contains a list of all arguments passed to the function.
The arguments object is not an array. Although syntactically it has the same features as an array, for example it has a length property. But it does not inherit from Array.prototype, in fact, it is an object.
Therefore, we cannot directly use some array methods such as push, pop or slice on arguments. So in order to use these methods, we need to convert it to a real array.
Convert to array
The following code will return an array containing all elements of the arguments object.
Array.prototype.slice.call(arguments);
Since the conversion is very slow, this is not recommended in performance-critical programs.
Pass parameters
The following is a recommended way to pass the arguments object from one function to another.
Another clever method is to use call and apply at the same time to quickly create an unbound outer method.
The relationship between function parameters and arguments attribute
Thearguments object creates getter and setter methods for both its own properties and the formal parameters of its functions.
Therefore, modifying the formal parameters of a function will affect the property values of the corresponding arguments object, and vice versa.
Performance issues
arguments will not be created in only two situations, one is declared as a local variable inside the function, and the other is used as a formal parameter of the function. Otherwise, the arguments object is always created.
Since getter and setter methods are always created with the arguments object, using arguments itself has little impact on performance.
However, there is one situation that seriously affects the performance of Javascript, and that is the use of arguments.callee.
In the above code, the foo function is no longer a simple inline extension, because it needs to know both itself and its caller. This not only negates the performance gain brought by inline expansion, but also destroys the encapsulation of the function, because the function itself may need to depend on a specific calling context.
Therefore, it is recommended that you try not to use arguments.callee.
The above is all about the Javascript arguments object. Do you guys understand it thoroughly? Simply put
arguments refers to the parameter object of the function (referring to the actual parameters passed in)
arguments.length refers to the length of the parameter object of the function
arguments[i] refers to the value of the i-th parameter (the first one is 0)