最近对于 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>