Use and distinction of this call and apply in JavaScript

  • 2020-12-09 00:45:01
  • OfStack

Reasons for learning:

In the previous STUDY of JavaScript, this,call and apply always confused me, but they are widely used. So it took a day to understand this,call,apply.

There are also many books for reference, mainly JavaScript Design Patterns and Development Practices, supplemented by JavaScript Advanced Programming and JavaScript You Don't Know. These three books are of great help to my understanding of this,call and apply.

this

First, let's talk about this.

In the description of this in JavaScript Design Patterns and Development Practices, I think there is one sentence that strikes at the heart of this. That is:

this of JavaScript always points to 1 object
In practical application, this can be divided into the following four directions:

As a method call to an object As a normal function call Constructor call Call apply and call

Next, let's look at the first 3 points, and the apply and call calls from point 4, which will be covered in detail in sections call and apply.

1. Method calls as objects

Description: When called as an object method, this points to the object.
For example:


/**
 * 1. As a method call to an object 
 *
 *  When called as an object method, this Points to the object. 
 */

var obj = {
 a: 1,
 getA: function() {
  console.log(this === obj);
  console.log(this.a);
 }
};

obj.getA(); // true , 1

2. As a normal function call

Note: When called as a normal function, this always points to the global object (window in the browser).
For example:


/**
 * 2. As a normal function call 
 *
 *  Not called as an object property ,this Must point to 1 An object. That's the global object. 
 */

window.name = 'globalName';

var getName = function() {
 console.log(this.name);
};

getName(); // 'globalName'

var myObject = {
 name: "ObjectName",
 getName: function() {
  console.log(this.name)
 }
};

myObject.getName(); // 'ObjectName'

//  So this is essentially putting function() {console.log(this.name)}
//  That's the sentence assigned to theName . thisName When called from a global object, it is read naturally from the global object name value 
var theName = myObject.getName;

theName(); // 'globalName'

3. Constructor call

Note: When invoked as a constructor, this points to the returned object.
For example:


/**
 * 3. Called as a constructor 
 * 
 *  When invoked as a constructor, this Points to the returned object. 
 */

var myClass = function() {
 this.name = "Lxxyx";
};

var obj = new myClass();

console.log(obj.name); // Lxxyx
console.log(obj) // myClass {name: "Lxxyx"}

However, if other return objects are specified manually in the constructor, this will not work.
If return has a different data type, that's fine.


var myClass = function() {
 this.name = "Lxxyx";
 //  join return Is returned by another object. this It doesn't work. 
 return {
  name:"ReturnOthers"
 }
};

var obj = new myClass();
console.log(obj.name); // ReturnOthers

4. Call and Apply

The use of Call and Apply is one sample. Specifies the direction of this in the function body.

The difference between Call and Apply

Call: The first parameter is the point of this, and the parameters to be passed to the function take 1 input 1.
Apply: The first parameter is a point to this, the second parameter is an array, and all parameters are passed in first order.

If the first argument is null, this points to the call itself.

1. Change the this orientation

Note: This is the most common use of call and apply. Used to change the direction of this in the body of the function.
For example:


var name = "GlobalName"

var func = function() {
 console.log(this.name)
};

func(); // "GlobalName"

var obj = {
 name: "Lxxyx",
 getName: function() {
  console.log(this.name)
 }
};

obj.getName.apply(window) // "GlobalName"  will this Point to the window
func.apply(obj) // "Lxxyx"  will this Point to the obj

2. Borrowing methods from other objects

Here, let's start with an anonymous function that executes immediately:


(function(a, b) {
 console.log(arguments) // 1,2
 //  call Array The prototype method of 
 Array.prototype.push.call(arguments, 3);
 console.log(arguments) // 1,2,3
})(1,2)

The function has the arguments attribute, while arguments is an array of classes.
But arguments cannot call the methods of the array directly, so we will use call or apply to call the prototype method of the Array object.
The principle is also easy to understand, for example, the push method was just called, and the push method is in the Google v8 engine, the source code looks like this:


function ArrayPush() {
 var n = TO_UINT32(this.length); //  be push Length of object 
 var m = % _ArgumentsLength(); // push Number of parameters 
 for (var i = 0; i < m; i++) {
  this[i + n] = % _Arguments(i); //  Copy the element 
 }
 this.length = n + m; // correction length attribute 
 return this.length;
}

It is only related to this, so as long as it is a class array object, you can call the related methods to handle it.

This part content is more complex, add oneself level also is not quite enough. Therefore, I recommend qualified students to buy relevant books, or wait for my subsequent blog posts.

feeling

Through the study of this part, I have deepened my understanding of JavaScript. To see, is the most intuitive performance, excellent framework source code, are no longer being this, call, apply, bind around dazed. Still very happy ~

In the next period, I will explore CSS in depth. After all, JavaScript learned, and HTML and CSS can't be left behind.


Related articles: