Before we get to this, let’s read a passage:

Once upon a time there was a mountain,
There is a temple in the mountains,
Call the temple,
There were many monks in the temple,
The monks loved the temple,
So monks often carried water to the temple.

If you follow the above pronunciation, you will find that there will be a lot of temple, which is not only not consistent with ordinary reading and writing habits, but also very jumbled.

This and we write code in the usual, too, if you are creating an object, the object inside a function, the function will be called in several attributes of the object, if we always write the name of this attribute, attribute name for a long time, not only the invalid code quantity increase, will make the code is not clean, if we use this, The effect of the result will be greatly optimized. Let’s take an in-depth study of the use and binding of this

The default binding

function girl(){
    consloe.log(this)
}
girl()
Copy the code

Now the function doesn’t have a direct caller, and then when the function is called, it points to the global window object,

Implicit binding

Var girl = {name: ' ', age: 18, detail() {console.log(' name '+ this.name) console.log(' age' + this.age)}} girl.detail()Copy the code

Here we create a girl object with properties and methods, and every time we call a method on that object, we implicitly bind it up to the object called by this

Hard binding

SayName () {console.log(this.log)}} var girl1 = {name: 'girl2'} var girl2 = {name: 'girl2'} var girl2 = {name: 'girl2'} } girlname.sayname.call (girl1) girlname.sayname.call (girl2) girlname.sayname.apply (girl1) girlName.sayName.apply(girl2)Copy the code

We create an object, then call our own methods through the object, and use the Call and apply methods to change the reference to this, so we can bind to whatever object we want

Constructor binding

Function Love (name) {this.name = name this.sayname = function () {console.log(this.name)}} var name = 'small white' let XiaoHong = new Love(' xiaoHong ') xiaohong.sayname ()Copy the code

This code will print a little red, because when we create an instance of the constructed function, we create a new space, and why is the little red, because we have copied a Love.

Of course, if you want to use this keyword well, you must be familiar with the call,apply, and bind methods, which I will not go into too much here. I will explain these three methods in detail later