经常遇到有关js函数的调用问题,特别有关apply()与call()方法,特此总结一下,希望大家指导与指正。
1.call()与apply()
看了那么多的解释,感觉越解释越糊涂呀,那就用通俗易懂的大白话说一下吧:
obj.call(thisObj, arg1, arg2, ...);
obj.apply(thisObj, [arg1, arg2, ...]);
两者作用一致,都是把obj(即this)绑定到thisObj,这时候thisObj具备了obj的属性和方法。或者说thisObj继承了obj的属性和方法。
唯一区别是apply接受的是数组参数或者arguments,call接受的是连续参数,当参数不确定时用arguments
参考别人的例子:
unction add(j, k){
return j+k;
}
function sub(j, k){
return j-k;
}
我们在控制台运行:
add(5,3); //8
add.call(sub, 5, 3); //8
add.apply(sub, [5, 3]); //8
sub(5, 3); //2
sub.call(add, 5, 3); //2
sub.apply(add, [5, 3]); //2
这个例子特别好:
var zhangfei = { father: { name: '你管得着么' } };
var guanyu = { father: { name: function() { return '你猜,你猜,你猜猜猜' } } };
[zhangfei, guanyu].map(function(who) { var name = fatherName.call(who); return Object.prototype.toString.call(name) === "[object Function]" ? name() : name; }); //["你管得着么", "你猜,你猜,你猜猜猜"]
这个例子也不错:
function changeStyle(attr, value){this.style[attr] = value;}
var box = document.getElementById('box');
window.changeStyle.call(box, "height", "200px");
继承:
//这个就是cat继承了Animal的属性和方法
function Animal(name){
this.name = name;
this.showName = function(){
alert(this.name);
}
}
function Cat(name){
Animal.call(this, name);
}
var cat = new Cat("Black Cat");
cat.showName(); //Black Cat
this.name = name;
this.showName = function(){
alert(this.name);
}
}
function Cat(name){
Animal.call(this, name);
}
var cat = new Cat("Black Cat");
cat.showName(); //Black Cat
该篇文章举的部分列子来自:https://www.zhihu.com/question/20289071