Preface:

I hope you know something about function calls, this Pointers, call(), apply(), and bind() before you start reading this article. (Reproduced please indicate the source — Nuggets of jam)

Opening:

I’m going to explain a few concepts that you might find confusing as you read the rest of the article, and when you do, come back here.

  1. How to understand “pointing” and “pointer”? You might read something like “This is just a pointer to an object, even though we removed the pointer to the object, the object still takes up memory.”

For example: when we go to school (primary school), the teacher will arrange a fixed seat number for the students, the purpose is to facilitate the teacher to let the students answer the question without remembering the name of the student, directly call the number, improve efficiency. So, a seat number corresponding to each of the students, such as 1, 2, 3 respectively represent xiaoming, little red, small three, here need to know, xiaoming and seat number 1, 2, 3, little red, small three is not exactly the same thing, the former is a typical digital (digital object), the latter is real (object), but again there is a one-to-one relationship between, At this point, we can say that the number 1 points to Xiao Ming, the number 2 points to Xiao Hong, and the number 3 points to Xiao SAN (” pointing “is a verb). Then, in a graphical way, it would be 1-> Xiao Ming, 2-> Xiao Hong, and 3-> Xiao SAN. See, the arrow between the number and the object is a pointer (noun). In other words, “Pointers” are a nominal term for the relationship between numbers and objects.

  1. How to understand “execution environment”? You might read something like “When a function is called, it is pushed into its execution environment. What variables exist in the execution environment of the function?

For example: ECMAScript is a director, objects are actors (Object, Array, Math, etc.), and variables are props. Running JavaScript code is equivalent to “directing actors to perform a play on the stage with the help of certain props in accordance with the script”. We analyze this sentence, ECMAScript, objects, variables have corresponding metaphors, but what is the script and stage? Scripts are the rules in ECMAScript, and stages are what we call “execution environments”! In a drama, at different stages, actors and props need to be used are different. The so-called “you sing and I come on stage”, and the “execution environment” is also the performance stage of different objects at different stages, and variable props are stored in different stages.

  1. call().apply()The method is almost the same, just the way you pass the argument is different, the second argument is an array, so why should there be two things that are almost the same? Isn’t that the same wheel?

It takes an introduction to their usage scenarios to show you why:

The Math object has a Max () method that returns the largest of the numbers passed in:


 var max = Math.max(1.8.3.15.4.5); // Call Math Max () to get the maximum argument passed in and assign it to Max
 console.log(max); // Print out 15
 
Copy the code

The above example can be written with exactly the same effect as above:


  var max = Math.max.call(Math.1.8.3.15.4.5); // Call Math Max () to get the maximum argument passed in and assign it to Max (small action of function call)
 console.log(max); // Print out 15
 
Copy the code

So what I want to do is change the requirement, and I want you to combine the Max () method to find the largest number in an array of numbers. Easy, you might say, and offer these solutions!


var arr = [1.8.3.15.4.5]; // Declare an array expression
var max = Math.max.call(Math. arr);// ES6解 决 syntax ======
console.log(max); / / print 15

Copy the code

Yes, it fulfills the requirement intelligently. But remember what the second argument to apply() was? Array! Look at the code


var arr = [1.8.3.15.4.5]; // Declare an array expression
var max = Math.max.apply(Math, arr); / / the apply method
console.log(max); / / print 15

Copy the code

Is there that kind of “I just need, you just professional” feeling ~!


Body:functionCall the “little secret”

Don’t be intimidated by the opening paragraph, the text of this article is simple. This is something that tells you that you didn’t know when function was called.

Function properties this and arguments are not known to refer to until the function is executed (think about that).

1. General function calls (function calls in the global environment)

First, in general, we declare and execute functions in the global environment as follows:


function hello(someone) {
    console.log(this + "Hello?" + someone);
} // Function declaration

hello("Golden jam"); // Function call, print out //[object Window] Hello gold nuggets

Copy the code

In fact, when the function is executed internally, it also does a little trick, which is our little secret:


function hello(someone) {
    console.log(this + "Hello?" + someone);
} // Function declaration

hello.call(window."Golden jam"); // Function call, print out //[object Window] Hello gold nuggets

Copy the code

Do you see the point? When executed, this automatically points to the global object window (note that node is global), just as we would print this to point to window manually.

Then you might also argue that the book doesn’t say that in strict mode the “this” refers to undefinded, but that’s because in strict mode the behavior of a function call looks like this:


function hello(someone) {
    'use strict';
    console.log(this + "Hello?" + someone);
} // Function declaration

hello("Golden jam"); // function call, print out //undefined hello nuggets of jelly
hello.call(undefined."Golden jam"); // print out //undefined hello, nuggets of jelly

Copy the code

How’s it going? You feel like you just opened up?

2. Calls to object methods (calls to functions inside objects)

First, there is an object that normally calls something like this:


var person = {
    name: "Golden jam".hello: function(someone) {
      console.log(this + "Hello?"+ someone); }};// Normal call
 person.hello("world");// [object object] Hello world

Copy the code

With the decryption above, you can understand how the function behaves when called:


var person = {
    name: "Golden jam".hello: function(someone) {
      console.log(this + "Hello?"+ someone); }};/ / little affectations
 person.hello.call(person, "world");// [object object] Hello world

Copy the code

call().apply().bind()The principle is very simple ah!

After parsing the little secret of function calls above, we know that they all “secretly” call()!

Let’s look at their definitions in MDN again:

Call () definition

fun.call(thisArg, arg1, arg2, …)

parameter

ThisArg Specifies this when fun is run. If (thisArg = = undefined | null) this = window, if(thisArg == number|boolean|string) this == new Number()|new Boolean()| new String()

arg1, arg2, … Specifies the argument list.


The apply () is defined

func.apply(thisArg, [argsArray])

parameter

ThisArg optional. The this value used when the func function is run. Note that this may not be the actual value seen by the method: if the function is in non-strict mode, specifying null or undefined is automatically replaced with pointing to a global object, and the original value is wrapped

ArgsArray optional. An array or array-like object whose array elements are passed as individual arguments to the func function. If the value of this parameter is null or undefined, no arguments need to be passed in. Array-like objects can be used starting with ECMAScript 5. For browser compatibility, see the bottom of this article.


The bind () definition

function.bind(thisArg[, arg1[, arg2[, …]]])

parameter

ThisArg the value passed to the target function as this when calling the binding function. If the new operator is used to construct the binding function, this value is ignored. When using bind to create a function in setTimeout (provided as a callback), any raw values passed as thisArg are converted to Object. If bind’s argument list is empty, this executing the scope will be treated as thisArg for the new function.

arg1, arg2, … Arguments that are pre-added to the argument list of the binding function when the target function is called


Call (); / / Call (); / / Call (); / / Call (); / / Call (); This object is set for the function. The apply () in the same way! You just have to pay attention to the way it receives arguments.

What about bind()? We don’t want to assign this to a function at execution time. We want to fix this, so bind() internally assigns this by calling call() or apply(). Using a closure to hold this object (closures won’t be discussed here), here’s an example that mimics the bind() method:


// Define an object
var person = {
    name: "Golden jam".hello: function(thing) {
      console.log(this.name + "Hello?"+ thing); }};// Simulate the action of bind, receiving a function and this object (execution environment)
var bind = function(func, thisValue) {
    return function() {
        return func.apply(thisValue, arguments); // Note the use of apply() and arguments
    };
};
  
var boundHello = bind(person.hello, person);
boundHello("The world"); // Print out // Gold-digging jam hello world

Copy the code

How about, pretty simple!


Aside:thisWhat exactly is the object?

This object is the execution environment of the function. As I said, the execution environment is the stage, the function is the actor, and the variables that the function can call are the props needed for the performance. So what’s the point of changing the execution environment of a function? Let’s look at examples:


var nullArr = []; / / an empty array
var arrType = Object.prototype.toString.call(nullArr); // Call the method in the Object prototype, pointing the execution environment (this) to nullArr

console.log(arrType); Print // [object Array]
console.log(nullArr.toString()); // An empty string

Copy the code

First of all, we need to know,

  1. Object. Prototype is a terminal prototype Object for all objects, including property methods that are shared by all objects. Other objects can also override those methods in the terminal prototype Object

  2. Almost all reference objects have their own toString() overridden;

In the example above, the Object. The prototype. The toString () is the method of terminal prototype Object, and nullArr as an instance of Array, to call himself an Array. The prototype prototype of toString (); As you can see from the example, an empty Array calls its array. prototype toString() to an empty string

Under special circumstances, that we want to array instance nullArr can use Object. The prototype. The toString () method, a simple method is to give the array to rewrite such a method, but if every need an array of the method to write again, it is not conform to the principle of reuse.

That we call the call () method to the Object. The prototype. The toString () method of execution environment (this) into nullArr actively, so this method can invoke the execution environment variables in the props (stage), from the perspective of nullArr, Equal to it with the Object. The prototype. The toString () method, in fact, it should be said with the Object. The prototype, the toString () method of the pointer (opening), pay attention to the pointer is a kind of relationship, not override the Object, (of course, This relationship only exists when the call() is executed, but not when it is finished – exit the stage.

Conclusion: It is simply false

After watching and understanding the above analysis, you might come to a conclusion: It’s not easy, it’s tricky! I have to admit, I lied. It’s not easy. But I’m trying to make you feel confident that things will be easier once they’re done.

I think people have a certain fear of unknown things, but if someone keeps saying it’s easy, then they don’t even have the courage to try!


Reference article:

  1. Dream Chaser – a summary of JavaScript call,apply, and bind methods
  2. Dream chaser – Understand the direction of this in JS completely without having to memorize it
  3. Yehuda Katz-Understanding JavaScript Function Invocation and “this” Yehuda Katz-Understanding JavaScript Function Invocation and “this”

QQ: 1448373124 (welcome to exchange front-end technology, welcome to point out the omissions in the article)

Reproduced please indicate the source — nuggets of jam