Literature of meaning

I have seen such a joke on the Internet, saying that a foreigner studied Chinese hard for ten years and went to China to take the Chinese test. The questions are as follows: Please explain the meaning of each “meaning” in the following.

Seeing this joke made me wonder how often you, as a front end, have encountered some kind of common interview question, such as please indicate all the output of the following code.

var name = 'window'

function Person(name) {
    this.name = name
    this.student = {
        name: 'obj'.hello1: function () {
            return function () {
                console.log(this.name)
            }
        },
        hello2: function () {
            return () = > {
                console.log(this.name)
            }
        }
    }
}
var person1 = new Person('person1')
var person2 = new Person('person2')

person1.obj.hello1()()
person1.obj.hello1.call(person2)()
person1.obj.hello1().call(person2)

person1.obj.hello2()()
person1.obj.hello2.call(person2)()
person1.obj.hello2().call(person2)
Copy the code

If you can give the correct answer quickly and effectively, then congratulations, you have studied this metaphysics very thoroughly. If you are dazzled, fine! Let’s take a closer look at the proper way to eat this.

1.thisTo come from

As one of the keywords in JavaScript, why is this a must-ask question for interviewers? Siege lions who understand and master it can point it out clearly, but half-understanding apes see it as a metaphysics, and don’t know why, through arrow functions and bind for this. First of all, we need to think: what problem does this appear to solve? We all know that this is a pointer to the object on which the function is called. Without this, all functions are represented by a specific object value, as follows:

var person = {
    name: "CassieLala".age: "8".grade: 2.hello: function () {
        console.log(`Hello, my name is ${person.name},
        I am ${person.age} years old, and I am in Grade ${person.grade}`);
    }
}
person.hello()
Copy the code

We can find that when we want to modify the object name, all object methods reference object fields need to be unified modification, maintenance trouble. If I have an object that always points to the current object, let’s say it’s called this, right? !!!!! I don’t know if everything’s gonna work out. So today, let’s take a hands-on look at who the ultimate object of this is bound to!

2.thisBinding rules

Before we figure out who this is bound to, let’s take a look at the rules for this binding. There are four binding rules for this: default binding, implicit binding, display binding, and new binding. Let’s take a look at their bindings and priorities one by one.

1. Default binding

Default bindings are defined as default rules that are generated when no other default rules are available (typically calls to separate functions). We can think of it as a call to a function that is not bound to a specific object. Here’s an example:

function hello() {
  console.log(this);
}
var name = "window";
hello(); // window
Copy the code

When we print the function in the browser environment, the output is Window. This is because in non-strict mode, this in the global scope points to the window, and name is also mounted on the global window. Note the above results and the results shown below, unless otherwise specified, are in a non-strict browser environment. In strict mode, an error is reported if an object is not declared. This is undefined globally in node.

2. Implicit binding

Implicit binding is defined as specifying that an object calls a method, i.e. there is an execution context. Example 1:

function hello() {
  console.log(this.name);
}

var name = 'window';

var person = {
  name: "CassieLaLa".hello: hello
}

person.hello(); // person
Copy the code

We can see from the above examples that although the Hello method is defined globally, its pointer object is on the person calling the method. This is what we call the concept of execution context. The object calling the method is the object, and this is the object inside the method. We just look at the final execution object. Example 2:

function hello() {
  console.log(this.name);
}

var name = 'window';

var gril = {
  name: "gril".hello: hello
}

var student = {
  name: "student".gril: gril
}

var person = {
  name: "student".student: student
}

person.student.gril.hello(); //gril
Copy the code

As you can see, this in Hello points to whoever is the executor of the final hello, regardless of the length of the preceding object call chain. Note Implicit binding carries the risk of pointer loss: when a reference to a method is assigned, the calling object before the assignment is lost. Example 3:

function hello() {
  console.log(this.name);
}

var name = 'window';

var person = {
  name: "student".hello: hello
}

var morning = person.hello;
morning(); // window
Copy the code

Although it seems that the assignment of Person. hello is a bit similar to that of Example 2 in scenario 1 above, we think fundamentally that the assignment is a reference to the Hello method of Morning, which is actually called by the hello method of Morning, which is mounted on the window, So the Person object here will be lost, and the output will be Window.

3. Display the binding

The above example describes that we found that implicit binding is easy to cause object loss. How can we do so that the required object is not lost? The answer is show bindings! Show binding word as its name, is I give you the object, you bind what object, I will need to bind the object to tell you! Hahaha, can’t we lose this again? ! Here we’ll highlight the three pointer guards in JavaScript: Call, apply, and bind. Look directly at the following example:

function hello() {
  console.log(this.name);
}

var name = 'window';

var person = {
  name: "student".hello: hello
}

var morning = person.hello;
var afternoon = person.hello;
var goodnight = person.hello;
morning.call(person); // student
afternoon.apply(person); // student
goodnight.bind(person)(); // student
Copy the code

Call and apply bind call and apply call and apply call and apply call and apply call and apply call and apply call and apply.

4. The new binding

JavaScript differs from other languages in that its class class is really just a class concept, essentially a constructor call to a function. If that’s a bit confusing, let’s take a look at the following example:

function Person(name) {
  this.name = name;
  console.log(this.name); // CassieLala
}

var name = 'window';

var person = new Person('CassieLala');
console.log('Hello,', person.name);  // Hello, CassieLala
Copy the code

From the above example, we can see that if we remove the new binding, implicit binding should be used here. Since there is no specific object binding for person, this refers to the window. This object will be attached by Prototype and bound to the function call’s this. The new object will be returned when no other objects are returned from the function. The result of the final call to name inside the function is CassieLala.

3. Which is better in binding rules?

We have introduced four different binding rules for this. What is the priority of these four binding rules? Let’s take a look at some examples:

function hello() {
    console.log(this.name);
}

var name = 'window';

var person = {
    name: "person".hello: hello
}

var student = {
    name: "student".hello: hello
}

var gril = {
    name: "gril".hello: hello
}

// Implicit -- implicit binding > default binding
person.hello(); // person
student.hello(); // student

// Show + implicit -- Show binding > Implicit binding > Default binding
person.hello.call(student); // student
student.hello.bind(person)(); // person

// new+ implicit -- new > implicit binding > default binding
new person.hello(); / / hello object
// new+ implicit -- error, new and display method cannot be shared
var hello = new hello.call(obj)
// display new first
var girl = hello.bind(student);
new girl(); // Hello object, indicating that the new binding is used
Copy the code

Through the above code test, it is not difficult to see that the priority of the four binding rules is: New > show binding > Implicit binding > default binding

Arrow function

Of course, in addition to the above four binding methods, ES6 provides a simple and straightforward this binding method: the arrow function, which ensures that this is always the parent of the current environment. Common usage scenarios include setTimeout, forEach and other related asynchronous functions. The following cases:

var name = 'window';
var person = {
    name: 'person'.hello: function () {
        setTimeout(function () {
            console.log(this.name);
        }, 0);
    },
    morning: function () {
        setTimeout(() = > {
            console.log(this.name);
        }, 0);
    }
}

person.hello() // window
person.morning() // person
Copy the code

As can be seen from the above example, hello uses an ordinary function, and the internal pointer of setTimeout itself points to the window object. When the arrow function is used in Morning, it uses the parent environment object of the current environment, the Person object, so the output is Person.

5. Think about

Finally, let’s think about why methods in VUE can only be written as normal function methods instead of arrow functions.

export default {
    data(){
        return {
            name: 'CassieLala'}},methods: {
        hello(){
            console.log(this.name); // CassieLala
        },
        morning: () = >{
            console.log(this.name); // undefined}}}Copy the code

In vue, all function methods in the methods object are iterated, and the publicThis object is bound by bind, and the this pointer in data is the same object. So we can access the name value of data directly in the method through this.name. If you change a normal method to an arrow function, and there is no this in the current scope, you have to go to the upper scope to find the Window object.

6. Finish scattering flowers ~~~

The above is all the content of our big talk this metaphysics, do not know to see here the ape children have not got evolution and soaring, I hope that later we see this, that this will not know its meaning. Ha, ha, ha, ha, ha, ha, ha, ha, ha.