分析this的指向问题

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <button>按钮</button>
</body>
</html>
<script>
    var btn = document.querySelector('button')
    // 函数中的this永指向调用者
    function fn () {
        console.log(this)
    }
    // var fn = function () {console.log(this)}
    // 1. window
    // fn()  // window.fn()
    // 2. 事件
    // btn.addEventListener('click', fn)

    // 实现一个功能 当点击按钮让btn背景色在1s之后变红
    btn.onclick = function () {
        // this --> btn对象
        // 方案一 借用变量
        /* var that = this
        setTimeout(function () {
            // 定时器中的this默认指向的是window
            // btn.style.background = 'red'
            // this.style.background = 'red'
            that.style.background = 'red'
        }, 1000) */
        // 方案二
        setTimeout(function () {
            // 通过bind改变了this的指向让this指向从默认的window指向btn
            this.style.background = 'red'
        }.bind(this), 1000)
        // 方案三 ES6的箭头函数
        setTimeout(() => {
            // 箭头函数没有this指向
            this.style.background = 'red'
        }, 1000)
    }


    // bind/call/apply 借用函数同时改变this指向
    // 当前这三个都是函数对象上的方法 fn.bind/call/apply
    // 他们三个第一个参数的都是要改变的this指向
    // 1. bind类 第二个参数是参数列表 不会立即帮我们调用
    var ff = function (a, b) {console.log(this, a, b,'这是ff')}
    // ff.bind({name: '松花江'}, 10, 12)() // bind()()
    // 2. call 第二个参数也是一个参数列表 但是他会立即调用
    // ff.call(['嗯'], 11, 13)
    // 3. apply 第二个参数是数组参数 但是他会立即调用
    // ff.apply(null, [13, 15]) // 此时的this是window null表示不改this指向

    // Math.max.apply(null, [11, 99, 22. 66, 77])
    // Math.max.apply({}, [11, 99, 22. 66, 77])

    // 对象中的this
    var obj = {
        name: 'suibian',
        say: function () {
            console.log(this, this.name)
        }
    }
    obj.say()  // this指向obj
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值