Hello, everyone. A few days ago in the process of development, and met this this difficult thing, although many big guys think this is the failure of javascript language, but no way, or in-depth understanding, so, or summary. Let’s examine several scenarios that this often encounters.

The default binding

Default binding usually means calling a method directly. In this case, this refers to a global object, such as:

function a(){
   console.log(this);
}

funciton b(){
   a();
}

b(); //window
Copy the code

Of course, the same is true for calls inside an object, such as:

function a(){
   console.log(this);
}

const b = {
  c(){
     a();
  }
}

b.c(); //window
Copy the code

Of course, in this case, I think there is also a significant connection to the static lexical scope, which I won’t go into here. If ‘use strict’ is added, then the calling method is always undefined. For example:

'use strict'
function a(){
   console.log(this);
}

const b = {
  c(){
     a();
  }
}

b.c(); //undefind
Copy the code

Implicit binding

This refers to the object in which it is defined. For example:

const a = {
 b(){
   console.log(this)
 }
}

a.b(); / / {b: ƒ}
Copy the code

Of course, object references are defined in the same way, for example:

function b(){
   console.log(this);
}

const a = {
 b
}

a.b(); / / {b: ƒ}
Copy the code

And you can actually see here that the lexical scope is not affected.

The new binding

This everybody affirmation is familiar with, after all interview ah want to take an examination, more is to write much. The first is the default action performed by the new argument:

  1. The Object (object.create (construction.prototype)) that creates the constructor’s prototype Object. This part is actually related to es6.
  2. Point the this of the constructor’s method to the object created in the first step and execute the constructor.
  3. If the constructor returns any other arguments, it returns this argument. If it does not, it returns the object of the first step after execution.

Boiled down to code:

function create (par = function() {},... args) {
  const create = Object.create(par.prototype);
  const res = par.apply(create, args);
  return res instanceof Object ? res : create;
}
Copy the code

So after the steps above, the this inside the constructor method must be determined. Of course, the class is the same in ES6, so I won’t expand it out here.

Mandatory binding

This is the preferred call,bind,apply, and other javascript frameworks, for example:

 function b(){
    console.log(this);
 }
 const a = { }
 
 b.call(a);
 b.apply(a);
 b.bind(a)()
Copy the code

As for the difference between these three methods, I believe that everyone knows the difference ~.

conclusion

That’s about it. I’m mainly referring to Javascript You Don’t Know, which is available on Github in Both Chinese and English. Although the Chinese translation is still so aunt meaning, obscure, but read several times or will shine at the moment.