this指向的几种情况
文章目录
结论总结如下:
1.正常情况下,this的指向要看函数在何处调用;
2.正常情况下,this都指向调用该方法的对象、实例或者构造函数;
3.如果方法在调用时,没有调用对象(例:fn( )),默认的this指向是window,但是需要注意,在严格模式下,却要指向undefined(但箭头函数和setTimeout是特殊情况);
4.箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this,因此箭头函数内的this要看该箭头函数的所在作用域的this指向;
5.setTimeout调用的代码运行在与所在函数完全分离的执行环境上,这会导致,这些代码中包含的 this关键字会指向window,即使是严格模式下也不受影响,但是如果涉及到箭头函数,则遵循箭头函数的规则;
6.构造函数this指向其实满足第2条规则,至于把方法赋值给一个新的变量,执行后this指向了undefined,是因为class构造函数遵循严格模式,也就是满足了第3条规则;
7.如果箭头函数、setTimeout、严格模式同时存在,其规则权重如下:箭头函数 > setTimeout > 严格模式
情况一:在函数中,this指向window。
->>但是在use strict模式下,this指向undefined。
->>但是在use strict模式下,箭头函数this仍然指向window
function app1() {
console.log(this)
}
let app2 = function () {
console.log(this)
}
let app3 = () => {
console.log(this)
}
app1()
app2()
app3()
//执行结果
Widnow
Widnow
Widnow'use strict'
function app1() {
console.log(this)
}
let app2 = function () {
console.log(this)
}
let app3 = () => {
console.log(this)
}
app1()
app2()
app3()
//执行结果
undefined
undefined
window情况二:在对象中,普通函数this指向该对象,箭头函数指向window
->>解构后,this都指向window
->>但是在use strict模式下,this指向undefined
->>但是在use strict模式下,箭头函数this仍然指向window
let Person = {
say: function () {
console.log(this)
},
speak:() => {
console.log(this)
}
}
Person.say()
Person.speak()
//执行结果
Person
Windowlet { say, speak } = Person
say()
speak()
//执行结果
Window
Window'use strict'
let Person = {
say: function () {
console.log(this)
},
speak: () => {
console.log(this)
}
}
let { say, speak } = Person
say()
speak()
//执行结果
undefined
Window情况三:在定时器中,this指向window,即使是'use strict'模式下也一样
let Person = {
say: function () {
setTimeout(function () {
console.log(this)
})
}
}
Person.say()
//执行结果
Window情况五:定时器中使用箭头函数,this指向与箭头函数所在作用域的this指向保持一致(需要把箭头函数从定时器中拿出来看),即使是'use strict'模式下也一样
let Person = {
say: function () {
setTimeout(() => {
console.log(this)
})
}
}
Person.say()
//执行结果
Person情况六:在class类中
->>直接调用,this指向该实例;
->>但如果是构造函数内的静态方法,this指向该构造函数
->>将方法重新赋值后,无论何种方法,this指向undefined
class app {
constructor(name) {
this.name = name
}
say() {
console.log(this)
}
}
let person = new app('bob')
person.say()
let fn = person.say;
fn()
//执行结果
person
undefinedclass app {
constructor(name) {
this.name = name
}
static say() {
console.log(this)
}
}
app.say()
let fn = app.say;
fn()
//执行结果
app
undefined
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论