Description of the roles and differences between apply and call methods in javascript

  • 2020-03-30 01:45:53
  • OfStack

I. description of call and apply

1. Call and apply belong to a method of function.prototype, which is implemented by the JavaScript engine. As it belongs to function.prototype, every instance of Function object (which is every method) has the property of call and apply. Since they are properties of methods, they are of course used against methods, and the two methods are confusing because they do the same thing but are used differently.

Foo. call(this, arg1,arg2,arg3) == foo.apply(this, arguments) == this.foo(this, arg2,arg3);

3. Similarities: the two methods have exactly the same effect.

4. Differences: the parameters passed by the method are different.

Two, example code


<script type="text/javascript">
    function A(){
        this.flag = 'A';
        this.tip = function(){
            alert(this.flag);
        };
    }
    function B(){
        this.flag = 'B';
    }
    var a = new A();
    var b = new B();
    //a.tip.call(b);
    a.tip.apply(b);
</script>

3. Code interpretation (that is, explain the apply and call functions)

1. The example code defines two functions A and B, in which A contains the flag attribute and tip attribute (this attribute assigns A function), and in which B has A flag attribute.

2. Create objects A and B of A and B respectively.

3. Whether a.t IP. Call (b); And a.t IP. Apply (b); I'm going to pop up B.

4. It can be seen from the results that both call and apply can make B object call the tip method of A object and modify the current action object of this.


Related articles: