Article Directory
First, what call () and apply () is
Both are function object method will be executed when you call the function of these two methods
method if do not understand the function of this watch
Two, call () and apply () role in common
- 1. The first argument passed is an object
- 2. To change this pointer points, reusing existing methods, which object passed, this refers to which object
- 3. The parameters passed may utilize a solid after the first reference
Illustrates two common front
<script type="text/javascript">
//创建一个对象
obj={
name:"obj",
sayname:function(){
alert(this.name);
}
};
obj1={
name:"obj1"
};
obj.sayname.apply(obj1);//输出obj1
obj.sayname.call(obj1);//输出obj1
</script>
The first one thing in common: Parameter passing from the point of view, the first parameter is a call to apply the object
The second common: It can be seen from the output results, this method is obj1 Alert, which is changed by the call point and apply this method, from the point becomes point obj1 obj. this point blog
had no sayname obj1 method, by multiplexing method call and apply methods of obj .
The third common place to say the difference in
Three differences, call () and apply () of
Difference: you can use parameters passed after the first argument, the argument of different forms of mass
- call () method arguments may be sequentially transmitted after the object
- apply () method requires the argument is dispensed into a transfer array unified
for example
<script type="text/javascript">
function fun(a,b){
console.log("a="+a);
console.log("b="+b);
}
obj2={
name:"obj2"
};
fun.call(obj2,1,2);//输出a=1,b=2
fun.apply(obj2,[1,2]);//输出a=1,b=2
</script>
fun.call (obj2,1,2); // Output a = 1, b = 2
fun.apply (obj2, [1,2]); // Output a = 1, b = 2
from two lines can be seen, apply a desired parameter passed into the array
IV Summary
call () and apply () role in common
- 1. The first argument passed is an object
- 2. To change this pointer points, reusing existing methods, which object passed, this refers to which object
- 3. The parameters passed may utilize a solid after the first reference
the difference
- Different forms pass arguments, apply the method into a unified array