call()、apply()都是函数对象的一个方法,作用是改变函数的调用对象;
以另一个对象替换当前对象来调用该函数;
通过它们的第一个参数来指定函数的上下文;
二、语法
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
apply([thisObj[,argArray]])
参数说明:
第一个参数(thisObj):新指定的函数对象的上下文,如果没有提供参数,默认Globle对象
第二个参数:被调用方法的传参;
三、区别
call的arg传参需要一个个传,apply则直接传一个数组。
function hello (name, age){
console.log(name);
console.log(age);
}
hello.call(this,"tsrot", 24);
hello.apply(this,["tsrot",24]);
四、运用场景
1、实现继承
function Animal(name){
this.name = name;
this.showName = function(){
consloe.log(this.name);
}
}
function Cat(name){
Animal.call(this. name);// Cat继承了AnimaL的showName方法
}
var cat = new Cat('Black Cat');
cat.showName();//Black Cat
2、数组追加
var array1 = [1, 2, 3, 5];
car array2 = ["xie", "li", "qun", "tsrot"];
Array.prototype.push.aplly(array1,array2);
console.log(array1);//[1, 2, 3, 5, "xie", "li", "qun", "tsrot"]
3、获取数组中的最大值和最小值
var num = [1,3,5,7,2,-10,11];
var maxNum = Math.max.apply(Math, num);
var minNum = Math.min.apply(Math, num);
console.log(maxNum); //11
console.log(minNum); //-10
4、将伪数组转换为数组
var fakeArr = {0:'a',1:'b',length:2};
var arr1 = Array.prototype.slice.call(fakeArr);
console.log(arr1[0]); //a
var arr2 = [].slice.call(fakeArr);
console.log(arr2[0]); //a
arr1.push("c");
console.log(arr1); //["a", "b", "c"]
// 正常情况下使用变量保存 this 值
var foo = {
bar : 1, eventBind: function(){
var _this = this ;
$('.someClass').on('click',function(event) {
/* Act on the event */
console.log(_this.bar); //1
});
}
}