this改向

// 函数调用圆括号时(函数名称+括号),函数的this是window对象
        // function fn(){
        //     console.log(this)
        // }
        // window.fn()

        // 函数作为一个对象的方法,对象打点调用,函数的this就是这个对象
        // let obj = {
        //     name: '柯真宏',
        //     say(){
        //         console.log(this)
        //         console.log(this.name + '今晚单身真好,不仅可以学习,还可以省钱!')
        //     }
        // }
        // obj.say()

        // 函数是事件处理函数时,函数的this就是触发这个this的对象(通过事件调用函数,this指向的是当前事件的调用者)
        // document.querySelector('button').onclick = function(){
        //     console.log(this)
        // }

        // 定时器调用函数时,this是window对象
        // setInterval(function(){
        //     console.log(this)
        //     console.log(666)
        // }, 1000)

        // 数组中存放的函数,被数组索引之后加圆括号调用,this就是这个数组
        function fn(){
            console.log(this)
            console.log('我是数组中的函数')
        }
        let arr = ['a', 'b', fn]
        //arr[arr.length-1] --- fn
        arr[arr.length-1]()
//bind()方法:修改函数或方法中的this为指定的对象,并且会返回一个修改后的之后的新的函数给我们
        //参数1表示要把当前的this改变成那个对象
        //参数2表示要传递的参数
        let obj = {
            name: '邢晨'
        }
        // function fn(a, b){
        //     // console.log(this)
        //     // console.log(a, b)

        //     console.log(this.name + '嘿嘿')
        // }
        //改变this指向
        // let res = fn.bind(obj, 10, 20)
        // res()

        //call()方法: 修改函数或方法中的this为指定的对象,并且会立即调用修改之后的函数
        //参数1表示要把当前的this改变成那个对象
        //参数2表示要传递的参数
        // function fn(a, b){
        //     console.log(this)
        //     console.log(a, b)
        // }
        // fn.call(obj, '哈哈', '嘻嘻')

        //apply()方法: 修改函数或方法中的this为指定的对象,并且会立即调用修改之后的函数
        //注意点:apply()方法参数必须是一个数组进行传递,要不然会报错
        //参数1表示要把当前的this改变成那个对象
        //参数2表示要传递的参数
        function fn(a, b){
            console.log(this)
            console.log(a, b)
        }
        fn.apply(obj, [10, 20])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值