call and apply

As a method call and apply this to modify the interior point method

var obj = {
  name : "obj"
}
function sum(a, b){ console.log(
this); } SUM (); // window.test (); return window object
sum.apply (obj); // returns the object obj

The difference is that a different call and apply the parameters passed, the method may pass a plurality of call parameters (object ,,,), apply the method only two arguments (object, array). The first parameter is the object introduced this point to modify the parameters

There obj = {
    name : "obj"
}
function sum(a , b){
    console.log(a + b);
    console.log(this);
}
sum.call (obj, . 1 , 2 );     // Call method may pass a plurality of parameters 
var ARR = [ 2 , . 3 ];
sum.apply (obj, ARR);     // Apply method with two arguments. The second array, sequentially passing method call shape parameter
// true array into an array of dummy
 // 1. The method calls the push array
 // 2. apply the method, this shift is the object obj
 // 3. Remove array elements are passed to push arr process parameter 
var arr = [ 2 , 3 ];
[].push.apply(obj, arr);
console.log(obj);     //输出{0: 2, 1: 3, name: "obj", length: 2}

 

 

Guess you like

Origin www.cnblogs.com/renhaooh/p/11984772.html