The call() apply() bind() method in JS changes this

Posted by maheshbaba on Wed, 05 Jan 2022 06:40:19 +0100

We all know the direction of this:
Always adhere to a principle: this always points to the object that was invoked at last, because the object of calling function is different, which leads to the different direction of this.

However, the direction of this can be changed by using call apply bind:

  1. call method

Syntax: fun call(thisArg, arg1, arg2, …)

  • thisArg: the value of this specified when the fun function runs

  • arg1, arg2: other parameters passed

  <script>
        function f1(name, age, sex) {
            this.name = name;
            this.age = age;
            this.sex = sex;
        }

        function f2(name, age, sex) {
            f1.call(this, name, age, sex);
        }
        var son = new f2('Zhang San', 18, 'male');
        console.log(son);      //f2
   </script>

Summary:

  • Call can call a function or change the point of this in the function
  • The main function of call is to realize inheritance
  1. apply method:

Syntax: fun apply(thisArg, [argsArray])

  • thisArg: the value of this specified when the fun function runs
  • argsArray: the passed value must be included in the array
<script>
    var o = {
        name: 'xxxx'
    }
    function init(arr) {
        console.log(this);
        console.log(arr);     
    }
    init.apply(0, ['xxxx']);          
    // Calculate size value
    var arr = ['12', '113', '124', '125', '126', '127', ''];        //'' defines itself as 0

    var max = Math.max.apply(this, arr) //Using apply to calculate the maximum value
    console.log(max);

    var min = Math.min.apply(this, arr) //minimum value
    console.log(min);            //The output is 0
</script> 

Summary:

  • apply can call the function or change the point of this in the function

  • The return value is the return value of the function, because it is the calling function

  • The main function of apply is related to arrays, such as using math Max() finds the maximum value of the array

Note: in JS strict mode, if the first parameter of the apply() method is not an object, it will become the owner (object) of the called function. In "non strict" mode, it will become a global object.

  1. bind method

fun.bind(thisArg, arg1, arg2, ...)

  • thisArg: the value of this specified when the fun function runs
  • arg1, arg2: other parameters passed
<script>
     var o = {
            name: 'andy'
        };

        function fn(a, b) {
            console.log(this);
            console.log(a + b);
        };
        var f = fn.bind(o, 1, 2);
        f();                                     //You need to call it yourself
        
        var btns = document.querySelectorAll('button');
        for (var i = 0; i < btns.length; i++) {
            btns[i].onclick = function() {
                this.disabled = true;

                // var that=this
                setTimeout(function() {
                // that.disabled = false;
                    this.disabled = false;         //this in the timer points to window   
                }.bind(this), 2000);
            }
        }
    </script>

Summary:

  • Returns a copy of the original function modified by the specified this value and initialization parameters
  • So when we just want to change the point of this and don't want to call this function, we can use
    bind

4: The difference between call apply bind:

  <script>
        var Person = {
            a: 1,
            b: 2,
            sum: function(a, b) {
                var self = this;

                function A() {
                    return self.a;
                }

                function B() {
                    return self.b;
                }
                console.log(a, b);
                return A() + B();
            }
        }
        var obj = {
            a: 1,
            b: 1
        };

        console.log(Person.sum.call(obj, 3, 4)); //3 4 2
        console.log(Person.sum.apply(obj, [5, 6])); //5 6 2 
        console.log(Person.sum.bind(obj, 7, 8)()); //7 8 2
    </script>

Similarities:

  • Can change the this point inside the function

Differences:

  • Call and apply will call the function and change the internal this point of the function
  • The parameters passed by call and apply are different. The parameters aru1, aru2... Passed by call must be in the form of array [arg]
  • bind will not call the function. You can change the internal this point of the function

About arrow function and its internal use_ this = this to modify the direction of this, you can refer to this link

Topics: Javascript bind