Simple contrastive analysis of the use of Apply,call and this in JavaScript _javascript tips

Source: Internet
Author: User

1.apply definition

Apply: Call the function and replace the value of the function with the specified object, replacing the parameters of the function with the specified array.
Syntax: Apply ([Thisobj[,argarray]])
Thisobj
Optional. The object to use as the This object.

Argarray
Optional. A set of parameters to pass to the function.

2.call definition

Call: Invokes the method of an object, replacing the current object with another object.
Syntax: Call ([thisobj[, arg1[, arg2[, [, Argn]]]]
Thisobj
Optional. The object that will be used as the current object.

Arg1, Arg2, argn.
Optional. The argument list that will be passed to the method.

3. The difference between the two

The second argument to call can be any type, and the second argument to apply must be an array or a arguments.
There are also differences in definitions.

4. Example Analysis

(1) Official examples:

 function callMe (arg1, arg2) {var s = "";
  S + + ' This value: ' + this;
  S + + "<br/>";
    For (i in callme.arguments) {s + = "arguments:" + callme.arguments[i];
  S + + "<br/>";
return s;
} document.write ("Original function: <br/>");
document.write (CallMe (1, 2));

document.write ("<br/>");
document.write ("Function called with apply: <br/>");
document.write (Callme.apply (3, [4, 5]));
document.write (Callme.call (3, 4, 5)); Output://Original function://This value: [Object Window]//arguments:1//arguments:2/function called with AP Ply://This value:3//arguments:4//Arguments:5 

First to apply: Define: Invoke function and replace the This value of the function with the specified object
Call the function CallMe, replacing this in the CallMe function with the specified object 3, where this is changed from the previous [object Window] to 3.
The first call: Definition: A method that invokes an object and replaces the current object with another object.
Invokes the object CallMe method, replacing the object in CallMe with another object, 3.
As can be seen from the analysis of these results, both use the object in the specified object or the specified value to change this in the object.
It can also be said that an object in a function (this) "hijacked" another object (this) to perform in the function.
In fact, this raises a question: what is this? Why is it so important to change the direction of the mind again and again?

(2) Example:

function Zqz (a,b) {return
  alert (a+b);
}
function Zqz_1 (a,b) {
  zqz.apply (zqz_1,[a,b])
}
zqz_1 (1,2)  //->3 

Profiling: Calling a function by definition and replacing the this value of the function with the specified object,
This calls the function ZQZ and replaces the This value of the ZQZ function with the specified object zqz_1.

Note that the function name in JS is actually an object, because the function name is a reference to the Funtion object!

function Add (A, B)
{
 alert (a + B);
}
function Sub (A, b)
{
 alert (a-b);
}
Add.call (Sub, 3, 1); 4

Profiling: By definition: Invokes an object's method, replacing the current object with another object.
This is the method that invokes the object add and replaces the current object sub with the Add object;

One more example:

function Zqz (a,b) {
  this.name=a;
  this.age=b;
  Alert (this.name+ "" +this.age);
}
function Zqz_1 (a,b) {
  zqz.apply (this,[a,b])   //We can also write  zqz.apply (this,arguments) 
}
zqz_1 (" Nic ","  //nic 12

Profiling: Calling a function by definition and replacing the this value of the function with the specified object,
This invokes the function ZQZ, using the specified object, this replaces the function ZQZ.

One more example:

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

Analysis: Definition: Invokes the method of an object, replacing the current object with another object.

Invokes the method of the Fun1 object, replacing the object in the current Fun1 with a Window object.
Invokes the method of the Fun1 object, replacing the object in the current Fun1 with the object in input.
Invokes the method of the Fun1 object, replacing the object in the current Fun1 with an object in the newly created obj.

Let's take a look at a question asked by a netizen:

The call method can be used to invoke a method instead 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 supplied, the Global object is used as a thisobj.

And then I did it myself. wrote a case, the writing is different from the imagination; the following code

 function parent ()
 {
 alert (this.name);
 }
 function Child ()
 {
 var name = ' John ';
 };
 
 

He's exporting the child why not John according to the above sentence the parent context has become a child

And the child has a name value that should be exported is John. Ask the Great God to explain

 
 function parent ()
 {
 alert (this.name);
 }
 function Child ()
 {
 this.name = ' john ';
 };
 var p1 = new Child ();
 
 

This can output John for what?

What the hell is going on, let's see

The use of call and apply is to use variables as function names. such as a function callback function. The specific usage is: executed function. Call (A,b,c ...), where a is in the executed function this requires the specified object, can be null, and other parameters as parameters of the executed function. Apply usage is similar, except that the second argument is an array.

An example is provided:

function DoPost (url,param,callback) {
  //Here processes POST request
  var str = xhr.responsetext;
  Callback.apply (This,[str]);//equivalent to calling callback (str) and setting this to Dopost object in callback

Related Article

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.