关于javascript:this指向的几种情况

论断总结如下:
1.失常状况下,this的指向要看函数在何处调用;
2.失常状况下,this都指向调用该办法的对象实例或者构造函数
3.如果办法在调用时,没有调用对象(例:fn( )),默认的this指向是window,然而须要留神,在严格模式下,却要指向undefined(但箭头函数和setTimeout是非凡状况);
4.箭头函数不会创立本人的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
Window
let { 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指向window,即便是’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
undefined
class app {
    constructor(name) {
        this.name = name
    }
    static say() {
        console.log(this)
    }
}

app.say()
let fn = app.say;
fn()

//执行后果
app
undefined

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理