js 中的 this
发布日期:2021-05-08 00:13:22 浏览次数:15 分类:原创文章

本文共 1623 字,大约阅读时间需要 5 分钟。

最近对于 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
内联事件

上一篇:js 中获取时间戳的方式
下一篇:js 的事件委托

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年04月08日 23时43分09秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章