关于前端:通俗易懂的this指向总结

this指向是工作和面试中常常会遇到的问题。

依据集体了解,简略从3个方面来总结一下this的指向问题。

1. this指向的论断

1. 若是全局函数,并且没有间接调用它的对象,没有严格模式,则默认指向全局 windowglobal

2. 若是全局函数,并且没有间接调用的对象,严格模式下,this指向undefined

3. 箭头函数的this,是在函数定义时依据上下文函数决定的。若是全局定义,则this指向windowglobal。若上下文有函数环境,则指向该上下文的this

4. 应用call扭转this的指向取决于call的第一个参数,若第一个参数是null,还是会绑在全局的

2. 一般函数和箭头函数的this指向

联合上面的示例加深了解。

(1) 若是全局函数,并且没有间接调用它的对象,没有严格模式,则默认指向全局 window

function hello1(){
    console.log('我是hello1 this:',this) // window
}
hello1() 

(2)若是全局函数,并且没有间接调用的对象,严格模式下,this指向undefined

function hello2(){
    'use strike';
    console.log('我是hello2 this:',this) // undefined
}
hello2()  

(3)用obj间接调用hello3函数,则第一个this指向obj
setTimeOut外面的箭头函数,this指向obj
setTimeOut外面的匿名函数,this指向window

因为:箭头函数的this,是在定义箭头函数时依据上下文函数环境决定,该箭头函数定义在函数外部,上下文执行环境在hellow3函数内,所以指向hello3的this

var obj = {
    name:'aaa',
    hello3(){
        console.log('我是hello3 this:',this); // obj
        setTimeout(()=>{
            console.log('我是hello3 外面箭头函数settimeout this:',this); // obj
        },3000)

        setTimeout(function (param) {  
            console.log('我是hello3 外面匿名函数settimeout this:',this); // window
        },2000)
    }
}

obj.hello3()

(4)hello4是一般函数,间接被obj调用,则this执行objhello5是箭头函数,this应该指向下限文函数中的this,这里上下文没有函数对象,所以默认为window

 var obj2 = {
    name:'aaa',
    hello4(){
        console.log('我是hello4 this:',this); // obj
    },
    hello5:()=>{
        console.log('我是hello5 this:',this);  // window
    },
}

obj2.hello4();
obj2.hello5();

(5)应用call 绑定this,取决于call的第一个参数,若第一个参数是null,还是会绑在全局的。

function foo(){
    console.log(this)
}

foo(); // global
foo.call(1); // [Number: 1]
foo.call({a:10},1); // { a: 10 }
1. foo.call(null,1); // global

评论

发表回复

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

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