SoFunction
Updated on 2025-04-08

Analysis of usage of arguments and this object in JavaScript

This article describes the usage of arguments and this object in JavaScript. Share it for your reference, as follows:

There are two special objects inside the function: arguments and this.

1. arguments object

The js function does not mind how many parameters are defined, nor does it care how many parameters are passed in. That is to say, even if the defined function only receives 2 parameters, it may not necessarily pass 2 parameters when called, because the function parameters of js are represented internally using an array, and this parameter array can be accessed through the arguments object in the function body. Therefore, js functions can use named parameters without explicitly.

When a function is called, the passed parameters will be saved in the arguments array object, and the arguments can access all the parameter lists passed to it when the function is called.

arguments are an array object of class, because arguments can access each element through square bracket syntax and have onelengthproperty, but it lacks all array methods, so it is not a real array.

Use arguments to implement a sum function:

function add() {
 var sum = 0;
 for (var i = 0, len = ; i < len; i++)
  sum += arguments[i];
 return sum;
}

Although the main purpose of arguments is to save function parameters, this object has anothercalleeProperties, which are pointers to functions that own the arguments object.

useProperties can implement a factorial function:

function factorial(num) {
  if (num <= 1)
  return 1;
  else
  return num * (num - 1);
}

Notice:

In strict mode, it cannot be usedAttributes cannot be assigned values ​​to the arguments object, and the arguments object cannot be used to track changes in parameters.

The same effect can be achieved using named function expressions:

var factorial = (function func(num) {
 if (num <= 1)
  return 1;
 else
  return num * func(num - 1);
));

Since the js function has no signature (definition of the type and number of accepted parameters), the js function is not overloaded. For functions with the same name, the function defined later will overwrite the function defined first. Of course, overloading of the method can be mimicked by checking the type and number of incoming parameters and making different reactions.

2. This object

Unlike other languages, this in JavaScript always points to an object, and specifically points to which object is dynamically bound based on the execution environment of the function at runtime, rather than the environment when the function is declared.

  • This is an attribute of the execution context, whose value is determined when entering the context and remains unchanged during context runs.
  • This is dynamically bound, that is, bound during runtime.
  • This can be a global object, a current object, or any object, depending on how the function is called. There are several ways to call functions: as ordinary function calls, as object method calls, as constructor calls, andcall()andapply()Called.

(1) Called as a normal function

When a function is not called as an object's property, that is, it is called directly, this will be bound to the global object. In the browser's JavaScript, the global object is a window object.

var name = "Alice";
function getName (name) {
 return ;
}
alert(getName()); // Output: Alicevar name = "Alice";
var obj = {
 name: 'Bruce',
 getName: function(name) {
  return ;
 }
};
var getName = ();
alert(getName()); // Output: Alice

In the above two examples, this is bound to the global object.

var firstname = "A";
var lastname = "B";
var person = {
 firstname : "Alice",
 lastname : "Bruce",
 setName : function(firstname, lastname) {
  var setFirstName = function(firstname) {
    = firstname;
  };
  var setLastName = function(lastname) {
    = lastname;
  };
  setFirstName(firstname);
  setLastName(lastname);
 }
};
("Cindy", "David");
alert(firstname);//Cindy
alert(lastname);//David
alert();//Alice
alert();//Bruce

Problem: For functions defined inside a function, this may also point to the global, and what is desired is that this of the internal function is bound to the object corresponding to the external function.

Cause: Internal functions can never directly access this variable in external functions.

Solution: In the external function body, when entering the internal function, save this into a variable and then use the variable.

var firstname = "A";
var lastname = "B";
var person = {
 firstname: "Alice",
 lastname: "Bruce",
 setName: function(firstname, lastname) {
  var that = this;
  var setFirstName = function(firstname) {
   = firstname;
  };
  var setLastName = function(lastname) {
   = lastname;
  };
  setFirstName(firstname);
  setLastName(lastname);
 }
};
("Cindy", "David");
alert(firstname);//A
alert(lastname);//B
alert();//Cindy
alert();//David

(2) Called as object method

When a function is called as an object method, this is bound to the current object.

var firstname = "A";
var lastname = "B";
var person = {
 firstname : "Alice",
 lastname : "Bruce",
 setName : function(firstname, lastname) {
   =  + firstname;
   =  + lastname;
 }
};
("Cindy", "David");
alert(firstname);//A
alert(lastname);//B
alert();//AliceCindy
alert();//BruceDavid


This is bound to the current object, that is, the person object.

(3) Called as a constructor

There are no classes in JavaScript, but objects can be created from the constructor, and new operators are also provided, making the constructor look more like a class.

When creating a new object using the constructor, you can point this to the newly created object to avoid this in the function pointing to the global.

var name = "Alice";
function Person(name) {
  = name;
}
var person = new Person("Bruce");
alert(name);//Alice
alert();//Bruce

Use the constructor to create a new object person, this points to the person.

When calling the constructor with new. One more thing to note is that if the constructor explicitly returns an object of object type, the result returned by the constructor will be this object, not this.

function Person() {
  = "Alice"
 return {
  name: "Bruce"
 }
}
var person = new Person();
alert();//Bruce

(4) Call() and apply() calls

call()andapply()Switch the context of function execution, that is, the object bound to this; this points toapply()andcall()The first parameter in.

function Person(name) {
  = name;
  = function(name) {
   = name;
 }
}
var person1 = new Person("Alice");
var person2 = {"name": "Bruce"};
alert("person1: " + ); // person1: Alice
("David");
alert("person1: " + ); // person1: David
alert("person2: " + ); // person2: Bruce
(person2, ["Cindy"]);
alert("person2: " + ); // person2: Cindy

apply()Apply the person1 method to person2, and this is also bound to person2.

3. This priority

(1) Whether the function is called in new, if it is, this is bound to the newly created object.

(2) Whether the function is called through call or apply, if so, this is bound to the specified object.

(3) Whether the function is called in a certain context object, if so, this is bound to the context object.

(4) If none of them are used, use the default binding. If in strict mode, bind to undefined, otherwise bind to global object.

4. This is missing problem

eg1:

var person = {
 name: "Alice",
 getName: function() {
  return ;
 }
};
alert(()); // Alice
var getName = ;
alert(getName()); // undefined

When called()hour,getName()The method is called as the property of the person object, so this points to the person object;

When referring to another variable getName, and callgetName()When, it is called as a normal function, so this points to the global window.

eg2:

&lt;div &gt;The right way&lt;/div&gt;
&lt;script&gt;
 var getId = function(id) {
  return (id);
 };
 alert(getId('div').innerText);
&lt;/script&gt;
&lt;div &gt;The wrong way&lt;/div&gt;
&lt;script&gt;
 var getId = ;
 alert(getId('div').innerText); // throw an exception&lt;/script&gt;

Problem: The first segment call is normal, but the second segment call will throw an exception.

Reason: Many engines()This is needed in the internal implementation of the method. This originally expected to point to a document, when the first piece of code isgetElementById()When a method is called as a property of a document object, this inside the method does point to the document, and in the second code, getId is used to reference it.After that, getId is called, and it becomes a normal function call. This inside the function points to the window, not the original document.

Solution: Use apply to pass document as this into the getId function to correct this.

&lt;div &gt;How to correct&lt;/div&gt;
&lt;script&gt;
  = (function(func) {
  return function() {
   return (document, arguments);
  };
 })();
 var getId = ;
 alert(getId('div').innerText); // throw an exception&lt;/script&gt;

For more information about JavaScript, readers who are interested in reading this site's special topic:JavaScript object-oriented tutorial》、《Summary of common JavaScript functions techniques》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《Summary of JavaScript traversal algorithm and skills"and"Summary of JavaScript mathematical operations usage

I hope this article will be helpful to everyone's JavaScript programming.