js 中的 this

最近对于 js 的 this 有些困惑.

说下目前, 我理解的一些场景的 this 的具体表示含义

  • 在函数外, this 总是表示 window 对象
  • 在函数内, this 与调用者有关
  • addEventListener 的回调函数, this 表示当前触发事件的元素
  • 内联事件, 例如元素的 onclick 属性, 如果 this 作为参数, 表示当前触发事件的元素, 如果 this 在函数内, 那么表示的是对象 (例如 window 对象), 而不是触发事件元素

<button onclick="foo1()">按钮 1</button>
<!--内联事件, this 作为参数表示当前元素, this 如果在函数里使用, 表示调用者对象, 例如 window 对象-->
<button onclick="foo2(this)">按钮 2</button>
<button id="btn3">按钮 3</button>

<script>

    /*

    https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this

    在函数外, this == windows
    函数内: this 与函数被调用方式有关

    addEventListener 回调函数的 this 表示触发事件的元素
    内联事件 (例如 onclick)
        如果 this 作为参数, 那么表示触发事件的元素
        如果 this 在函数内, 那么表示全局对象或者自定义对象, 而不是触发事件的元素

    类中 this 表示当前实例

     */

    // 在函数外, this == windows
    console.log(`this == window: ${this == window}`);

    this.b = '你好鸭'
    console.log(`window.b: ${this.b}`)

    // window 永远与 globalThis 相等
    console.log(`window == globalThis: ${window == globalThis}`)

    function foo1() {
        // 这里的 this 表示 window

        // 如果是严格模式, 那么是 undefined, 而不是 window
        // "use strict";
        console.log(`foo1() = ${this}`)
        return this
    }
    function foo2(dom) {
        // 这里的 this 表示 window

        // 如果是严格模式, 那么是 undefined, 而不是 window
        // "use strict";
        console.log(`foo2() = ${dom}`)
        return this
    }

    console.log(`foo1() == window: ${foo1() == window}`);

    // addEventListener 回调函数的 this 表示当前触发元素
    document.querySelector('#btn3').addEventListener('click', function () {
        console.log(`#btn3 this: ${this}`)
    });

</script>

函数外 this
addEventListener
内联事件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值