在javascript中apply、call、bind都是為了改變某個函數(shù)運(yùn)行時的上下文而存在的,簡單的說,就是為了改變函數(shù)體內(nèi)部this的指向。
一、apply()和call()
call()和apply()是Function對象的方法,每個函數(shù)都能調(diào)用。
語法:
//apply
fun.apply(context, [arg1, arg2, ...])
//call
fun.call(context, arg1, arg2, ...)
第一個參數(shù)就是指定的執(zhí)行上下文,后面部分用來傳遞參數(shù),也就是傳給調(diào)用call和apply方法的函數(shù)的參數(shù)。
注:apply()方法接收的是包含所有參數(shù)的數(shù)組,而call()方法接收的是參數(shù)列表。
說白了,就是調(diào)用函數(shù),但是讓它在你指定的上下文下執(zhí)行,這樣,函數(shù)可以訪問的作用域就會改變。
二、bind()
bind()是es5中的方法,用來實(shí)現(xiàn)上下文綁定。bind()和call()與apply()傳參類似,不同的是,bind是新創(chuàng)建一個函數(shù),然后把它的上下文綁定到bind()括號中的參數(shù)上,然后將它返回。
bind()不會執(zhí)行對應(yīng)的函數(shù),而是返回新創(chuàng)建的函數(shù),便于稍后調(diào)用;call()和apply()會自動執(zhí)行對應(yīng)的函數(shù)。
語法:
fun.bind(context, arg1, arg2, ...)
栗子:
var person = {
name:'tom',
age:18,
say:function(sex){
console.log('My name is ' + this.name + ' age is ' + this.age + ' and sex is ' + sex)
}
}
var person1 = {
name:'Nicholas',
age:20
}
person.say('女');
person.say.call(person1, '女');
person.say.apply(person1, ['女']);
person.say.bind(person1, '女');
結(jié)果:

上面代碼用三種方法改變了person.say()的this指向,使其指向了person1。
可以看到使用bind()方法不會執(zhí)行對應(yīng)的函數(shù),而是返回一個新創(chuàng)建的函數(shù),讓該函數(shù)的this指向括號內(nèi)的第一個參數(shù)。
為了看到效果,我們可以使用
person.say.bind(person, '女')(); //執(zhí)行返回的函數(shù)
//輸出My name is Nicholas age is 20 and sex is 女
三、js實(shí)現(xiàn)bind()方法
在不支持bind()方法的瀏覽器中,我們要使用這個方法,就只能自定義一個bind()方法,實(shí)現(xiàn)一樣的功能。
if (!Function.prototype.bind) {
Function.prototype.bind = function(context) {
var self = this; //設(shè)置變量接收當(dāng)前this
var args = Array.from(arguments); //將偽數(shù)組轉(zhuǎn)換成數(shù)組
return function() {
return self.apply(context, args.slice(1));
}
};
}
如果不存在bind()方法,就在函數(shù)對象的原型上自定義函數(shù)bind()。這樣每個函數(shù)就可以使用這個bind()方法了。
此處的bind返回一個函數(shù),該函數(shù)把傳給bind的第一個參數(shù)context當(dāng)做執(zhí)行上下文。排除第一項,將之后的部分作為第二部分參數(shù)傳給apply。即實(shí)現(xiàn)了bind()方法。
arguments是一個偽數(shù)組,里面存儲傳給bind的參數(shù),通過將偽數(shù)組轉(zhuǎn)換成數(shù)組,既可以使用數(shù)組的方法。
四、js實(shí)現(xiàn)apply()方法
Function.prototype.myApply =function(context,arr){
context = Object(context) || window;
context.fn = this;
var result;
if(!arr){
result= context.fn();
}else{
var args = [];
for(var i=0;i<arr.length;i++){
args.push('arr['+i+']');
}
result = eval('context.fn('+args.toString()+')')
}
delete context.fn;
return result;
};
var q = {name:'chuchu'};
var arg1 = 1;
var arg2= [123];
function eat(n,m){
console.log(this,n,m);
}
eat.myApply(q,[arg1,arg2])

四、js實(shí)現(xiàn)call()方法
Function.prototype.myCall = function(){
var arr = Array.from(arguments);
var context = arr[0];
var args = arr.slice(1);
return this.apply(context, args);
};
var q = {name:'chuchu'};
var arg1 = 1;
var arg2= [123];
function eat(n,m){
console.log(this,n,m);
}
eat.myApply(q,arg1,arg2);
