1.普通模式
<button id="app">点击</button>
<script>
// 1. 普通函数 this ---> window
function fun() {
console.log('普通函数', this)
}
fun()
// 2. 立即执行函数 this -----> window
;(function () {
console.log('立即执行函数', this)
})()
// 3. 定时器 this ----> window
setTimeout(() => {
console.log('定时器', this)
}, 0)
//4. 对象的方法 this ----> obj
const obj = {
say() {
console.log('对象的方法', this)
}
}
obj.say()
// 5. 构造函数不加new this ----> window
function Fruit(params) {
this.params = params
console.log('构造函数不加new', this)
}
Fruit('apple')
// 6. 构造函数加new this ---> 实例对象
function Person(params) {
this.params = params
console.log('构造函数加new', this)
}
const people = new Person('people')
// 7. 箭头函数 this ----> 箭头函数定义的位置的上下文this
const f = () => {
console.log('箭头函数', this)
}
f()
// 8. arguments[0]() this ---> 指向的是 arguments这个对象
function func() {
arguments[0]()
}
function fun1() {
console.log('arguments[0]()', this)
}
func(fun1, 1, 2, 3)
// 9. 数组元素是函数 this ---> 这个数组
function fun2(params) {
console.log('数组元素是函数', this)
}
const arr = [fun2, 1, 2, 3]
arr[0]()
// 10. 事件处理函数 this ---> 被绑定的 DOM元素
document.querySelector('#app').onclick = function () {
console.log('事件处理函数', this)
}
</script>
2.严格模式
<button id="app">点击</button>
<script>
'use strict'
// 1. 普通函数 this ---> undefined
function fun() {
console.log('普通函数', this)
function f() {
console.log('f', this)
}
f()
}
fun()
// 2. 立即执行函数 this -----> undefined
;(function () {
console.log('立即执行函数', this)
})()
// 3. 定时器 this ----> window
setTimeout(() => {
console.log('定时器', this)
}, 0)
//4. 对象的方法 this ----> obj
const obj = {
say() {
console.log('对象的方法', this)
}
}
obj.say()
// 5. 构造函数不加new this ----> undefined
function Fruit(params) {
// this.params = params
console.log('构造函数不加new', this)
}
Fruit('apple')
// 6. 构造函数加new this ---> 实例对象
function Person(params) {
this.params = params
console.log('构造函数加new', this)
}
const people = new Person('people')
// 7. 箭头函数 this ----> 定义位置上下文的this 全局:this 指向 window
const o = {
sing: function () {
console.log('o对象', this)
const f = () => {
console.log('o对象里面的箭头函数', this)
}
f()
}
}
const f = () => {
console.log('全局作用域下的箭头函数', this)
}
f()
o.sing()
// 8. arguments[0]() this ---> 指向的是 arguments这个对象
function func() {
arguments[0]()
}
function fun1() {
console.log('arguments[0]()', this)
}
func(fun1, 1, 2, 3)
// 9. 数组元素是函数 this ---> 这个数组
function fun2(params) {
console.log('数组元素是函数', this)
}
const arr = [fun2, 1, 2, 3]
arr[0]()
// 10. 事件处理函数 this ---> 被绑定的 DOM元素
document.querySelector('#app').onclick = function () {
console.log('事件处理函数', this)
}
</script>