首先我们看call()函数的用法;
call(obj,arg1,arg2,arg3);
apply(obj,[arg1,agr2,agr3]);
我们看最普通的函数;
function main(){
var str = "hello";
console.log(str);
}
main(); //hello
如果使用call会怎样?
function main(){
var str = "hello";
console.log(str);
}
main.call(); //hello
效果是完全一样的,我们再来试试带参数的;
function main(arg1,arg2){
var str = arg1+arg2;
console.log(str);
}
main.call(null,"hello"," world!"); //hello world!
main.apply(null,["hello"," world!"]); //hello world!
使用第一个参数的情况
var person = {};
person.name = "xiao ming";
function say(arg1,arg2){
console.log(arg1+"_"+arg2+"_"+this.name);
}
say.call(person,"nihao","wo jiao") //nihao_wo jiao_xiao ming
say.apply(person,["nihao","wo jiao"]) //nihao_wo jiao_xiao ming
可见this被绑架了!
常见的用法;
/*
* 目的:我们要删除数组arr1中的第一个元素;
*/
// 写法1
var arr1 = ["a1","b2","c3"];
var returnvalue1 = arr1.shift();
console.log(returnvalue1); //a1
//写法2
var arr2 = ["a1","b2","c3"];
var returnvalue2 = Array.prototype.shift.call(arr2);
console.log(returnvalue2); //a1
function f1(){
console.log(this);
console.log(1);
}
function f2(){
console.log(this);
console.log(2)
}
f1.call(f1); //function f1(){ console.log(this); console.log(1); },1
f1.call.call(f2); //Window,2
要理解上面的东西需要模拟一个我们自己的call函数
Function.prototype.myCall = function(obj){
var args = Array.prototype.slice.call(arguments,1);
return this.apply(obj,args);
}
function f1(){
console.log(1);
}
function f2(){
console.log(2)
}
f1.myCall(f2); //1 相当于: f1.apply(f2);
f1.myCall.myCall(f2); //2 相当于: Function.prototype.myCall.myCall(f2); 相当于: Function.prototype.myCall.apply(f2); 相当于: f2.apply(); 相当于f2();
ps有参数版本;
Function.prototype.myCall = function(obj){
var args = Array.prototype.slice.call(arguments,1);
return this.apply(obj,args);
}
function f1(a){
console.log("1"+a);
}
function f2(a){
console.log("2"+a)
}
f1.myCall.myCall(f2,"hello"); 相当于:Function.prototype.myCall.myCall(f2,"hello"); 相当于:Function.prototype.myCall.apply(f2,["hello"]);相当于:f2.apply("hello");;
Class.creat();
Function.prototype.bind();