Change the pointing of this pointer inside the function

Posted Jun 15, 20202 min read

If there are any mistakes, please correct me.

call(), apply(), bind()

Usage of call()

var obj = {
    text:'My two hobbies are:'
}

function getHobby(a, b) {
    console.log(this.text + a +'and' + b)
}

getHobby.call(obj,'Football','Badminton')
//My two hobbies are:football and badminton

Usage of apply()

var obj = {
    text:'My two hobbies are:'
}

function getHobby(a, b) {
    console.log(this.text + a +'and' + b)
}

getHobby.apply(obj, ['football','badminton'])
//My two hobbies are:football and badminton

Usage of bind()

var obj = {
    text:'My two hobbies are:'
}

function getHobby(a, b) {
    console.log(this.text + a +'and' + b)
}

getHobby.bind(obj,'Football','Badminton')()
//My two hobbies are:football and badminton

Compared

  1. getHobby.call(obj,'Football','Badminton')
  2. getHobby.apply(obj, ['football','badminton'])
  3. getHobby.bind(obj,'Football','Badminton')()

Through the above comparison, it is not difficult to understand:

  1. The first parameter of the three is "pointing to this".
  2. call and bind are passed in after the first parameter is a parameter list. The second parameter of apply is the parameter array.
  3. call and apply are immediate calls. And bind returns the corresponding function, you need to call () yourself.

Fanwai

This point

To put it simply:By default, it points to the global, and the browser points to window. If the function is called by an object, it points to this object.

Take a look at the specific examples:

function xxx(){
  console.log(this)
}

xxx()

Print result of console

This points to window

var obj = {
  "a":10,
  xxx:function(){
    console.log(this)
  }
}

obj.xxx()

Printing result of console

xxx() is called by obj, so this points to obj

Explanation

In fact, this is not the normal form of calling, this is just a shorthand, the complete writing is as follows:

  1. By default, call(undefined)` will be called implicitly

    xxx()
    //Equivalent to
    xxx.call(undefined)

In the browser, if you pass in undefined, it will automatically point to window(in strict mode, if you pass in undefined, then you point to undefined)

  1. The function is called by an object, and implicitly calls call(this object)

    obj.xxx()
    //Equivalent to
    obj.xxx.call(obj)

So this points to obj.