preface

In this article, I will talk about js bind glue. In this article, I will talk about the updated version of BIND glue: call and apply methods.

According to? — > Why apply and call?

In “Interesting Talk on JS bind brand Glue”, I described the background of the birth of bind, Call and apply methods through the relevant history of JS. The common purpose of these three methods is to find a suitable family for js’s first-class citizen Function (specify this to Function). Since bind has already met its purpose, why do we need to create call and apply methods? What are the similarities and differences between these two methods and BIND? With a little doubt, and with the small life roam forward.

What? What are call and apply?

1, Chinese interpretation:

Call: call, call, visit

I don’t want to apply

It can be seen from the Chinese definitions of call and apply that the two methods have obvious connection characteristics, such as “call call” : who calls who? “Apply” : Who applies to who? A verb that is bound to have three elements: 1. Active connector, 2. Passive connector, 3. Intermediary connecting the two. The three definitions of call and apply are slightly different. The Chinese definition of bind has an obvious static connection feature (only connecting), while the Chinese definition of call and apply has an obvious dynamic connection feature (still being used after connecting). Therefore, in the use of the three methods, Bind is only responsible for connecting functions with corresponding objects. Call and apply are also responsible for connecting functions with corresponding objects on the spot.

2.

function.call(thisArg, arg1, arg2, ...);   // callgrammarfunction.apply(thisArg, [argsArray]);      // applygrammarCopy the code

ThisArg syntax can be found on MDN for details. Here are a few things to note about thisArg:

  • Do not pass, or pass null, undefined, this to the window object.
  • Pass the name of another function, fun2. This refers to this of function fun2.
  • The value is the original value (Number, String, Boolean), and this refers to the auto-wrapped object for that original value, such as Number, String, Boolean
  • Pass an object to which this in the function refers

In the above examples of thisArg parameters, we find a common fact: ThisArg parameter is an object, always with the original values corresponding to the original value of packing objects, function with the reference to the function object, no object is a global object, seemingly without object, actually also is to have the object, it is not hard to see, js is an object-oriented programming language, everywhere are objects, everything has its object, how about you, Are you seeing anyone?

3. Detailed description:

The call and apply methods are created to change the this value of a function, as follows:

  var obj = {
    age: 22
  }

  function say(name) {
    console.log('I am:' + name + '| this year: + this.age);
  }

  say.call(obj, 'jack'); / / I'm: jack | this year: 22
  say.apply(obj, ['mike']); / / I'm: mike | this year: 22
Copy the code
  • From the code, we can see that call and apply have the following similarities:
  1. The first parameter specifies the host object
  2. Run this function as soon as the new host object is specified
  • The only difference: Apply accepts arguments in array format, while Call accepts several arguments. My understanding of the two forms of parameter transmission is as follows: Apply with “awarded” meaning, like emperor raised (transfer) is a kind of top-down, the emperor raised will give you a list of some of what things are in the list, call a “calling” meaning (transfer) is a relatively close, you call a friend to come over, told his secret, you will consists of the secret one by one.

How? — > How to use call and apply?

The north wind blows:

Master summons a powerful storm from heaven and earth, dealing 60/85/135/160(+0.35) magic damage to multiple targets one by one.

Skills Demonstration:

var Master = {
  name: 'Summoner'
};
var target1 = 'enemy1';
var target2 = 'enemy2';
var target3 = 'enemy3';
var target4 = 'enemy4';
var target5 = 'enemy5';

function NorthernStorm(target1, target2, target3, target4, target5) {
  console.log(this.name + ' have slained an enemy ' + target1);
  console.log(this.name + ' have slained an enemy ' + target2);
  console.log(this.name + ' have slained an enemy ' + target3);
  console.log(this.name + ' have slained an enemy ' + target4);
  console.log(this.name + ' have slained an enemy ' + target5);
}

NorthernStorm.call(Master, target1, target2, target3, target4, target5);
Copy the code

Apply skills — Doomsday:

“Master” summons a powerful doomsday storm from heaven and earth that can be instantly applied to a target group, dealing 200/250/300/444(+1) AOE damage.

Skills Demonstration:

var Master = {
  name: 'Summoner'
};
var target1 = 'enemy1';
var target2 = 'enemy2';
var target3 = 'enemy3';
var target4 = 'enemy4';
var target5 = 'enemy5';

function PowerfulStorm(arr) {
  console.log(this.name + ' Penta Kill! ');
}

PowerfulStorm.apply(Master, [target1, target2, target3, target4, target5]);
Copy the code

Haha, ABOVE I used game skills to briefly demonstrate the use of call and apply methods, hoping to help you understand related concepts. In order to deepen understanding, I made several examples for several specific use scenarios:

1. Get the maximum/minimum value in the array

var nums = [11.15.2.20.10];

var max = Math.max.apply(null, nums);
var min = Math.min.apply(null, nums);

console.log(max); / / 20
console.log(min); / / 2
Copy the code

2. Convert function arguments to arrays

function func() {
  var args = Array.prototype.slice.call(arguments);
  console.log(args);
}
func('hello'.'world'); // ["hello", "world"]
Copy the code

3. Check whether it is in array format

var arr = [];
var res = Object.prototype.toString.call(arr); [[class]] = [toString] = [toString] = [toString]
console.log(res); // [Object Array]
Copy the code

I will not give too much description about the use of apply and call, because there are a lot of examples on the Internet. Before, I always felt that the use of JS call, apply and bind was awkward and ugly (I still feel that). Later, I felt much more comfortable after I learned to look at the world from another Angle.

var nums = [11.15.2.20.10];
var max = Math.max.apply(null, nums);
Copy the code

If this is null, the object referred to by this is the Window global object. 2, The Window object replaces the Math object with the Max method.

Window.max(nums);
Copy the code

Note: The above code is just an aid to understand that at runtime, the Max method will only exist briefly on the Window object. After the Max method is used once, the Max method will be deleted from the Window, so the function bound to the specified object by call and apply will not end up on the specified object.

conclusion

1. Bind, apply, call

  • Similarities: Both base on changing the this direction of the function
  • Difference:
    1. Call and applly execute the function immediately; bind simply binds the function and does not execute the function immediately
    2. Bind is the default parameter of the call/apply function. The call/apply parameter is the default parameter of the call/apply function. The call/apply parameter is the default parameter of the call/apply function.

Some ideas

I have always felt that bind, call, and apply are not comfortable to use. However, I have found that these three methods have many uses. For example, bind events in DOM objects, and call and apply can be used if you want to reuse certain functions. Js appear on the three methods is largely because of js use is the appearance of functional programming, but actually is object-oriented (lining of DOM object, data object, etc.), two programming ideas mixed together, mixed is no problem, but both mixed failed to good fusion, design the bind, apply, the call is to please both sides, But this kind of temporary compromise doesn’t work very well, because one mountain can’t be divided into two, and someone has to be the flower and someone has to be the leaf, right? Until the emergence of MVVM architecture represented by Angular, React and Vue and the new improved ES6 standard, front-end development has entered a new mode. MVVM architecture enables front-end development to better realize the “object-oriented” programming mode, while taking advantage of the related features of ES6 and taking into account the flexibility of functional programming. In React development, if you bind an anonymous function to an event, you need to bind it by hand. However, you can use the arrow function of ES6 to bind it like this:

<div onClick={(res) => {this.setState({name: 'jack'}); }} > Click Me </div>Copy the code

For example, in the call/apply example above, you can use the ES6 extension operator… To deal with instead:

// Convert arguments to an array
function func() {
  var args = ([...arguments]);
  console.log(args);
}
func('hello'.'world'); // ["hello", "world"]

// Find the maximum value of the array
var res = Math.max(... [2.20.22]);
console.log(res); / / 22
Copy the code

As JS continues to evolve, these three methods may still be useful in some scenarios currently under development, but in my view bind, apply, and Call as a “compromise” will slowly fade away, but I find it interesting to understand the wisdom and thinking of designers before they are forgotten.

conclusion

The article involves a lot of content, unavoidably there will be careless, hope rational correction, progress together oh.