Summary of the usage of call() method and apply() method in JS

Recently, I encountered the call() method and apply() method in JavaScript, and at some point these two methods are really very important, so let me summarize the use and differences of these two methods.

1. Each function contains two non-inherited methods: call() method and apply() method.

2. The same point: The effect of these two methods is the same.

Both call the function in a specific scope, which is equivalent to setting the value of the this object in the function body to expand the scope in which the function runs.

In general, this always points to the object on which a method is called, but when you use the call() and apply() methods, you change this pointer.


//Example 1
    <script>
        window.color = 'red';
        document.color = 'yellow';

        var s1 = {color: 'blue' };
        function changeColor(){
            console.log(this.color);
        }

        changeColor.call(); //red (parameters passed by default)
        changeColor.call(window);   //red
        changeColor.call(document); //yellow
        changeColor.call(this);     //red
        changeColor.call(s1);       //blue

    </script>

    // Example 2
    var Pet = {
        words : '...',
        speak : function (say) {
            console.log(say + ''+ this.words)
        }
    }
    Pet.speak('Speak'); // 结果:Speak...

    var Dog = {
        words:'Wang'
    }

    //Change the point of this to Dog
    Pet.speak.call(Dog, 'Speak'); //结果: SpeakWang

Example of using the apply() method:

  //Example 1
    <script>
        window.number = 'one';
        document.number = 'two';

        var s1 = {number: 'three' };
        function changeColor(){
            console.log(this.number);
        }

        changeColor.apply(); //one (default parameter)
        changeColor.apply(window);   //one
        changeColor.apply(document); //two
        changeColor.apply(this);     //one
        changeColor.apply(s1);       //three

    </script>

    // Example 2
    function Pet(words){
        this.words = words;
        this.speak = function () {
            console.log( this.words)
        }
    }
    function Dog(words){
        //Pet.call(this, words); //Result: Wang
       Pet.apply(this, arguments); //result: Wang
    }
    var dog = new Dog('Wang');
    dog.speak();

3. Difference: The way to receive parameters is different.

  • The apply() method  accepts two parameters, one is the scope of the function to run (this), and the other is an array of parameters.

Syntax:apply([thisObj [,argArray] ]); , call a method of an object, and replace the current object with another object.

Explanation: If argArray is not a valid array or arguments object, a 
TypeError will be raised, if neither argArray nor thisObj are provided, the Global object will be used as thisObj.

  •  The first parameter of the call() method is the same as that of the apply() method, but the parameters passed to the function must be listed.

Syntax:call([thisObject[,arg1 [,arg2 [,...,argn]]]]); , applies a method of an object and replaces the current object with another object.

Description:  The call method can be used to call a method in place of another object. The call method can change the object context of a function from the initial context to the new object specified by thisObj. If the thisObj parameter is not provided, the Global object is used for thisObj.

Use example 1:

function add(c,d){
        return this.a + this.b + c + d;
    }

    var s = {a:1, b:2};
    console.log(add.call(s,3,4)); // 1+2+3+4 = 10
    console.log(add.apply(s,[5,6])); // 1+2+5+6 = 14

Use example 2:

  <script>
        window.firstName = "Cynthia";
        window.lastName = "_xie";

        var myObject = {firstName:'my', lastName:'Object'};

        function getName(){
            console.log(this.firstName + this.lastName);
        }

        function getMessage(sex,age){
            console.log(this.firstName + this.lastName + " 性别: " + sex + " age: " + age );
        }

        getName.call(window); // Cynthia_xie
        getName.call(myObject); // myObject

        getName.apply(window); // Cynthia_xie
        getName.apply(myObject);// myObject

        getMessage.call(window,"female",21); //Cynthia_xie gender: female age: 21
        getMessage.apply(window,["female",21]); // Cynthia_xie gender: female age: 21

        getMessage.call(myObject,"unknown",22); //myObject gender: unknown age: 22
        getMessage.apply(myObject,["unknown",22]); // myObject gender: unknown age: 22

    </script>
Thanks to the original author

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324815246&siteId=291194637