call/apply/bind方法的异同

  • 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 则是立即调用 。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值