全局
console.log(this)//Window
函数内
// 1.普通函数的this指向window
function fn1() {
console.log('fn1', this)
}
fn1()//Window
// 2.箭头函数的this指向window
let fn2 = () => {
console.log('fn2', this)
}
fn2()//window
对象内
- 对象中的普通函数,this指向obj
- 对象中的箭头函数,this指向Window
let obj = {
fn1: function () {
console.log('obj--fn1', this)//对象中的普通函数,this指向obj
},
fn2: () => {
console.log('obj--fn2', this)//对象中的箭头函数,this指向Window
},
obj1: {
fn1: function () {
console.log('obj1--fn1', this)//this指向obj1
},
fn2: () => {
console.log('obj1--fn2', this)//对象中的箭头函数,this指向Window
}
}
}
obj.fn1()//obj
obj.fn2()//Window
obj.obj1.fn1()//obj1
obj.obj1.fn2()//Window
function fn1() {
console.log('fn1', this)
}
let obj = {
fn3: (function () {
console.log('obj--fn3立即执行函数', this)
})(),
fn4: fn1(),
fn5: function () {
console.log('obj--fn5')
}
}
//立即执行函数会立即执行(即使没有调用fn3),并且把其之后的fn1也执行,但是不会执行fn5
//直接调用fn3会报错
//obj.fn3()//Uncaught TypeError: obj.fn3 is not a function
//obj.fn3//程序会忽视这句话,直接跳过不报错
![]()
- 对象中立即执行函数的执行顺序:从上到下依次执行到该对象的创建位置时,先执行立即执行函数,再执行对象调用的其他方法,注意,立即执行函数会把在其之后的代码也执行(如果可以执行的话)