JS 中改变函数的this指向,call,apply,bind方法的使用和区别

JS 中改变函数的this指向,callapplybind方法的使用和区别

1. call()方法 文档说明
语法
  1. function.call(thisArg, arg1, arg2, ...)
  2. thisArg 是想要将this指向的那个对象或者方法
  3. arg1,arg2...传递的参数
使用,使用call之后函数会立即调用
  1. 在没有使用call的时候fn函数中的this指向的是window
    function fn(a , b) {
        console.log(this) // window
        console.log(a + b) // 4
    }
    fn(2,2)
    
  2. 使用call之后,函数会立即执行,fn函数中的this指向被改变,指向了obj对象
    const obj = {
        name: "小火车"
    }
    function fn(a , b) {
        console.log(this) // obj
        console.log(a + b) // 4
    }
    fn.call(obj,2,2)
    
  3. 常用在组合继承中改变this指向
    function Father(name,age) {
        this.name = name,
        this.age = age
    }
    Father.prototype.sing =function(){
        console.log("我会唱歌")
    }
    function Son(name,age) {
        Father.call(this,name,age)
    }
    const user = new Son("小火车",24)
    console.log(user.name) // 小火车
    
2.apply()方法 文档说明
语法
  1. func.apply(thisArg, [argsArray])
  2. thisArg 是想要将this指向的那个对象或者方法
  3. argsArray 一个数组或者类数组对象
使用,使用apply之后函数也会立即调用
  1. 在没有使用apply的时候fn函数中的this指向的是window
    function fn(a , b) {
        console.log(this) // window
        console.log(a + b) // 4
    }
    fn(2,2)
    
  2. 使用apply之后,函数会立即执行,fn函数中的this指向被改变,指向了obj对象
    const obj = {
        name: "小火车"
    }
    function fn(a,b) {
        console.log(this) // obj
        console.log(a + b) // 4
    }
    fn.apply(obj,[2,2])
    
  3. 常结合数组一起使用,可以直接使用一些方法寻找数组的最大值最小值等等
    const array = [1,88,51,2]
    let max = Math.max.apply(Math,array)
    console.log(max) // 88
    
3. bind()方法 文档说明
语法
  1. function.bind(thisArg[, arg1[, arg2[, ...]]])
  2. thisArg 是想要将this指向的那个对象或者方法
  3. arg1,arg2...传递的参数
使用,使用bind()方法之后函数不会立即执行,但是bind()方法是使用最多的改变this指向
  1. 在没有使用bind的时候fn函数中的this指向的是window
    function fn(a , b) {
        console.log(this) // window
        console.log(a + b) // 4
    }
    fn(2,2)
    
  2. 使用bind之后,函数会立即执行,fn函数中的this指向被改变,指向了obj对象
    const obj = {
        name: "小火车"
    }
    function fn(a,b) {
        console.log(this) // obj
        console.log(a + b) // 4
    }
    const getFn = fn.bind(obj,2,2)
    getFn()
    
  3. 使用,结合setTimeout,比如按钮点击之后变成不可点击,三秒之后还原
    const btn = document.querySelector("button")
    btn.onclick = function() {
        this.disabled = true
        setTimeout(function(){
            this.disabled = false
        }.bind(this), 3000);
    }
    
  4. 因为bind()方法返回的就是一个函数,并且也不会立即执行,因此可以在计时器时间到之后再执行
三者之间的关系
共同点
  1. 都可以改变this的指向
区别
  1. callapply会立即调用函数,并且改变函数内部的this指向
  2. callapply传递的参数不同,call参数的形式是arg1, arg2, ...apply参数的形式必须是[arg1,arg2,...]
  3. bind不会立即调用函数,可以改变函数内部的this指向
使用场景
  1. call常用于组合继承
  2. apply经常和数组关联,借助一些函数得到数组的最大值最小值
  3. bind一般改变定时器内部的this指向
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值