js中call、apply、bind的区别

本文通过具体的JavaScript代码示例介绍了如何改变函数内部this的指向,并演示了使用call、apply及bind方法来实现不同上下文中的this指向调整。同时,展示了bind方法返回新函数的特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

var Person = {
name : 'alice',
say : function(txt1,txt2) {
console.info(txt1+txt2);
console.info(this.name);
}
}

var Dog = {
name : 'tom',
say : function(txt1,txt2) {
console.info(txt1+txt2);
console.info(this.name);
}
}
var arr = ['hello','hi'];
Person.say('hello','hi');
Dog.say('wang~','wang2~');
Person.say.call(Dog,'hello','hi');//Person.say内部的this指向了Dog,多个参数用逗号隔开
Person.say.apply(Dog,arr);//第二个参数是数组,参数数量可以是未知的
var PersonSay = Person.say.bind(Dog,'hello','hi');//不会立即执行,触发返回函数才会执行
PersonSay();



>>>hellohi
>>>alice
>>>wang~wang2~
>>>tom
>>>hellohi
>>>tom
>>>hellohi
>>>tom
>>>hellohi
>>>tom

转载于:https://www.cnblogs.com/Alice-Xu/p/8798503.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值