apply和call用法

apply语法


func.apply(name, [array])
  • 第一个参数指定函数体内this对象的指向.
  • 第二个参数为一个带下标的集合,可以是数组或类数组,apply方法把这个集合中的元素作为参数传递给被调用的函数

var func = function(a, b, c) {
  console.log([a, b, c]); // [1,2,3]
}
func.apply(null, [1,2,3])

call语法

  • 第一个参数:代表函数体内this指向
  • 第二个参数:数量不固定,每个参数依次传入函数 ```javascript

```

当使用call或则apply的时候, 如果我们传入的第一个参数是null. 函数体内的this会指向默认的宿主对象,在游览器中则是window

var func = function( a, b, c ){
  alert ( this === window );    // 输出true
};
func.apply( null, [ 1, 2, 3 ] );

但如果是在严格模式下,函数体内的this还是为null:


var func = function( a, b, c ){    
  "use strict";    
  alert ( this === null );     // 输出true
}
func.apply( null, [ 1, 2, 3 ] );

有时候我们使用call或者apply的目的不在于指定this指向,而是另有用途,比如借用其他对象的方法。
那么我们可以传入null来代替某个具体的对象:


Math.max.apply( null, [ 1, 2, 5, 3, 4 ] )    // 输出:5

call和apply的用途


var obj1={
  name: '李小龙'
}
var obj2={
  name: '萧薰'
}
window.name = 'window'
var getName = function(){
  console.log(this.name)
};
getName(); //输出:window
getName.call(obj1); //输出:李小龙
getName.call(obj2); //输出:萧薰

当执行getName.call( obj1 )这句代码时,getName函数体内的this就指向obj1对象

this 错误的情况


document.getElementById( 'div1' ).onclick = function(){    
alert( this.id );            // 输出:div1    
var func = function(){       
  alert ( this.id );        // 输出:undefined    
}    
func();
};

修正this


document.getElementById( 'div1' ).onclick = function(){    
var func = function(){        
  alert ( this.id );        // 输出:div1    
}    
func.call( this );
};

原文链接: http://www.jianshu.com/p/c942d58659c6

猜你喜欢

转载自www.cnblogs.com/lovellll/p/10109617.html