Home  >  Article  >  Web Front-end  >  The usage, meaning and difference between apply and call in JavaScript_javascript skills

The usage, meaning and difference between apply and call in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:30:56761browse

apply and call, their function is to bind the function to another object for operation. The only difference between the two is the way of defining parameters:
Function.prototype.apply(thisArg,argArray);
Function .prototype.call(thisArg[,arg1[,arg2…]]);
As you can see from the function prototype, the first parameter is named thisArg, that is, the this pointer inside all functions will be assigned the value thisArg , which achieves the purpose of running the function as a method of another object. Except for the thisArg parameter, both methods are parameters passed for the Function object. The following code illustrates how the apply and call methods work:

Copy the code The code is as follows:

//Define a function func1 with attribute p and method A
function func1(){
this.p="func1-";
this.A=function(arg){
alert (this.p arg);
}
}
//Define a function func2 with attribute p and method B
function func2(){
this.p="func2-" ;
this.B=function(arg){
alert(this.p arg);
}
}
var obj1=new func1();
var obj2=new func2();
obj1.A("byA"); //Display func1-byA
obj2.B("byB"); //Display func2-byB
obj1.A.apply(obj2 ,["byA"]); //Display func2-byA, where ["byA"] is an array with only one element, the same below
obj2.B.apply(obj1,["byB"]); / /Display func1-byB
obj1.A.call(obj2,"byA"); //Display func2-byA
obj2.B.call(obj1,"byB"); //Display func1-byB

It can be seen that after method A of obj1 is bound to obj2 for operation, the running environment of the entire function A is transferred to obj2, that is, the this pointer points to obj2. Similarly, function B of obj2 can also be bound to the obj1 object to run. The last 4 lines of code show the difference in the parameter forms of the apply and call functions.

Unlike the length attribute of arguments, the function object also has a length attribute, which represents the number of parameters specified when the function is defined, not the number of parameters actually passed when called. For example, the following code will display 2:
Copy the code The code is as follows:

function sum(a ,b){ return a b;}


Let’s take a look at the explanation of call in the JS manual:

call method
Call a method on an object to replace the current object with another object.
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
Parameters
thisObj
Optional. The object that will be used as the current object.
arg1, arg2, , argN
Optional. A sequence of method parameters will be passed.
Description
The call method can be used to call a method instead of another object. The call method changes the object context of a function from the initial context to the new object specified by thisObj.
If no thisObj parameter is provided, the Global object is used as thisObj.

To explain clearly, it is actually changing the internal pointer of the object, that is, changing the content pointed to by this of the object. This is sometimes useful in object-oriented js programming.

Quoting a code snippet on the Internet, you will naturally understand the reason after running it.


[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh to execute
]

The call function and the apply method The first parameter is the object to be passed to the current object, and this inside the function. The following parameters are the parameters passed to the current object.
Run the following code:

[Ctrl A select all Note:
If you need to introduce external Js, you need to refresh to execute <script> function Obj(){this.value="对象!";} var value="global 变量"; function Fun1(){alert(this.value);} window.Fun1(); //global 变量 Fun1.call(window); //global 变量 Fun1.call(document.getElementById('myText')); //input text Fun1.call(new Obj()); //对象! </script>]<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 can be seen that func and var have popped up respectively. At this point, you have an understanding of the meaning of each parameter of call.

Apply and call have the same function, but there are differences in parameters.
The first parameter has the same meaning, but for the second parameter:
apply passes in a parameter array, that is, multiple parameters are combined into an array and passed in, and call is used as call. Parameters are passed in (starting with the second parameter).
For example, the corresponding apply writing method of func.call(func1,var1,var2,var3) is: func.apply(func1,[var1,var2,var3])

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

javascript apply usage Supplementary
funObj.apply([thisObj[,argArray]])
application A method of an object that replaces the current object with another object.
When the method of functionObj is executed, the this object in the function will be replaced by thisObj.
thisObj Optional. The object that will be used as the current object.
argArray Optional. Array of arguments that will be passed to this function.
Copy code The code is as follows:

//Apply in object inheritance, do not use prototype, implicitly assigns the parent object properties to the child object
function par(name)
{
this.parname=name;
}
function child(chname,parname){
this.chname=chname;
par.apply(this,new Array(parname));
};
var o=new child("john","Mr john");
alert(o.parname ";" o.chname);
//apply can be used in general method calls
window.onunload=function()
{
alert(" unload event is fired!");
}
function sayBye(name,toName)
{
alert(name " says bye to " toName);
}
function sayEndBiz( name,toName,content)
{
alert(name " ends his talk about " content " with " toName);
}
function addTo(args,func)
{
var oldHandler=window.onunload||function(){};
window.onunload=function()
{
func.apply(window,args);
oldHandler.apply(window, args );
}
}
addTo(new Array("John","everyone"),sayBye);
addTo(new Array("John","everyone","deveopment strategy of the company"),sayEndBiz)
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn