- bind()方法会创建一个新函数,称为绑定函数,当调用这个绑定函数时,绑定函数会以创建它时传入 bind()方法的第一个参数作为 this
- 传入 bind() 方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数。
var aObj = {
fuc: function(){
return this.k
}
}
var bObj = {
k: 999
}
console.log(aObj.fuc()) //undefined
console.log(aObj.fuc.bind(bObj)()) // 999
function aObj(arg1,arg2,arg3){
console.log(arguments)
}
var bObj = {
k: 999
}
console.log(aObj.bind(bObj)(1,2,3,4)) //Arguments(4) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ]
call(obj,args1,args2...argsn) 第二个/第三个第四个...可以接受无限制个参数
apply(obj,[args1,args2...argsn]) 第二个参数接受的是个数组,例如:
定义一个 log 方法,让它可以代理 console.log 方法,并且输出前缀是zn的字符串:
function log(){
console.log.apply(console, arguments);
};
log(1); //1
log(1,2); //1 2
//arguments参数是个伪数组,通过 Array.prototype.slice.call 转化为标准数组,再使用数组方法unshift
function log(){
var args = Array.prototype.slice.call(arguments)
//args.unshift('zn')
console.log.apply(console, args)
}
三个方法的区别, 举个例子:
var ageObj = {
age: 30
}
var names = {
getAge: function(){
return this.age
}
}
console.log(names.age) //undefined
console.log(names.getAge.call(ageObj)) //30 将getAge的this指向变成ageObj
console.log(names.getAge.apply(ageObj)) //30 将getAge的this指向变成ageObj
console.log(names.getAge.bind(ageObj)()) //30 names.getAge.bind(ageObj) 是个函数,需要()来进行调用执行
总结:
- apply 、 call 、bind 三者都是用来改变函数的this对象的指向的;
- apply 、 call 、bind 三者第一个参数都是this要指向的对象,也就是想指定的上下文;
- apply 、 call 、bind 三者都可以利用后续参数传参;
- bind 是返回对应函数,便于稍后调用;apply 、call 则是立即调用 。