The usage meaning and difference of application and call in JavaScript

Source: Internet
Author: User

Call and apply the approximate use of the same, a simple look at the following example:

<input type= "text" id= "MyText"   value= "input text" ><script>    function Obj () {this.value= "Object! ";}    var value= "global variable";    function Fun1 () {alert (this.value);}    Window. Fun1 ();   Global variable    fun1.call (window);  Global variable    fun1.call (document.getElementById (' MyText '));  Input text    fun1.call (new OBJ ());   Object! </script>

We can call () and apply () as a method of an object, calling the function indirectly in the form of a calling method.

That is, the method is the original method, but the parameter is the parameter of the object contained in call.


The first parameter of the call function and the Apply method is the object to pass to the current object, and this inside the function. The arguments that follow are all arguments passed to the current object.

<script>   var func=new function () {this.a= "func"}    var myfunc=function (x) {        var a= "MyFunc";        alert (THIS.A);        alert (x);    }    Myfunc.call (func, "var");</script>

It is visible that Func and Var are ejected separately. Here you get a sense of the meaning of each of the call's parameters.


both apply and call are the same in effect, but they differ in parameters.
The meaning for the first parameter is the same, but for the second argument:
Apply passes in an array of parameters, which is the combination of multiple parameters into an array, and call is passed in as a call parameter (starting with the second argument).
such as Func.call (FUNC1,VAR1,VAR2,VAR3) corresponding to the wording of the Apply: Func.apply (Func1,[var1,var2,var3])


The benefit of using apply at the same time is that you can directly pass in the arguments object of the current function as the second parameter of apply

The usage meaning and difference of application and call in JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.