对call(),apply(),bind()方法的总结

call()的作用:
1 该变函数内部this的指向
2 函数立即执行(也就是说仅仅是用call()改变了一下this的指向,函数该怎么执行还是怎么执行)

    const obj = {
        name: "小凡"
    }
    function f1(x) {
        console.log(this === obj)//true
        console.log(x)
    }
    f1.call(obj, 1)//函数还是传参调用

3 call()同样可以用来继承

	function Parent(age, name) {
       this.age = age
       this.name = name
    }
    function Son(age, name) {
        Parent.call(this, age, name)
    }

    let p = new Son(19, "小凡")
    console.log(p)

apply()的作用
call()一样,唯一区别就是函数传参上的区别,在传递参数时用数组(最大区别)
主要应用:对数组进行操作,例如求数组中的最大值

	let arr = [1, 2, 3, 4, 5, 5, 69,]
    let max = Math.max.apply(Math, arr)
    console.log(max)

bind()作用
1 bind()方法不会立即执行(最大的区别)
2 同样可以改变this的指向
3 返回值为原函数改变this指向后的拷贝

	const obj = {
        name: "小凡"
    }
    function f1() {
        console.log(this.name)
    }
   const f2=f1.bind(obj)
    f2()//小凡

实际应用:bind()不会立即执行,正好合适

 	btn.addEventListener("click", function () {
        this.style.backgroundColor = "yellow"
        setTimeout(function () {
            this.style.backgroundColor = "red"
        }.bind(this), 3000)//函数外面的this,将函数里面的this替换
    })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值