bind, call, apply

bind, call, apply

call, apply, bind三种方法都可以用来改变当前函数的this指向。

先说区别

传参

1.第一个参数都是要更改调用的对象,不传递则默认指向window。
2.第二个及后续参数,call和bind相似,参数可以有多个,依次传入,apply只有两个参数,第二个参数必须是数组。

调用

call和apply调用后会自动执行调用的函数,bind会返回一个新的函数,并需要自动调用

let person = {
    name: "张三",
    age: 18,
    show(age) {
        console.log('年龄是' + age || this.age);
    }
}
let person2 = {
    name: '李四',
}
person.show.call(person2, 22); // 年龄是22
person.show.apply(person2, [23]); // 年龄是23
person.show.bind(person2, 24)(); // 年龄是24
使用案例

1.拼接数组

var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
// 使用concat方法
var arr = arr1.concat(arr2);
console.log(arr); // [1, 2, 3, 4, 5, 6]
// 使用扩展运算符
var arr3 = [...arr1, ...arr2]
console.log(arr3); // [1, 2, 3, 4, 5, 6]
// 使用apply
Array.prototype.push.apply(arr1, arr2);
console.log(arr1) // [1, 2, 3, 4, 5, 6]

2.实现继承

function Father(name, age) {
    this.name = name;
    this.age = age;
    this.address = '三里屯';
    this.show = function() {
        console.log('姓名' + this.name + ',年龄' + this.age + ',籍贯' + this.address);
    }
}
function Son(name, age) {
    Father.call(this, name, age);
}
var son = new Son("儿子", 13);
son.show(); // 姓名儿子,年龄13,籍贯三里屯

3.类数组调用数组的方法

let doms = document.getElementsByClassName('box');
Array.prototype.forEach.call(doms, function(f) {});

4.求数组的最大值

let arr = [1, 34, 23, 432, 123];
Math.max.apply(null, arr); // 432
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值