JavaScript中this的指向问题

165 阅读2分钟

一.全局环境中的this

在全局作用域下,this始终指向全局对象window,无论是否是严格模式!

console.log(this)         //window
window.console.log(this)  //window下的console方法

二.函数内的this

  • 普通函数内的this分为两种情况,严格模式下和非严格模式下。

1.严格模式下

//严格模式下
function test(){
   console.log(this);
}
test();//undefined
window.test();//window

直接test()调用函数,this指向undefined,window.test()调用函数this指向window。

2.非严格模式下

function test(){
console.log(this);
}
test();//window
window.test();//window

非严格模式下,通过test()和window.test()调用函数对象,this都指向window。

三.对象中的this

对象内部方法的this指向调用这些方法的对象,也就是谁调用就指向谁。

1.一层对象:

let obj = {
    name:"张三",
    skill:function(){
        name:"李四";
        console.log(this.name);
    }
}
obj.skill();//张三

调用obj.skill()方法,返回值为张三,说明此时this指向obj。

2.二层对象

let obj = {
    name:"张三",
    skill:function(){
        name:"李四";
        console.log(this.name);
    },
    obj2:{
        name:"王五";
        skill2:function(){
            name:"赵六";
            console.log(this.name);
        }
    }
}
obj.skill();//张三
obj.obj2.skill2();//王五

调用skill2()方法的顺序为,obj.obj2.skill2() ,返回值为王五,说明skill2()方法中的this指向obj2。

总结

1.函数的定义位置不影响其this指向,this指向只和调用函数有关。
2.多层嵌套的对象,内部方法的this指向离被调用函数最近的对象。

四.箭头函数中的this

箭头函数:this指向于函数作用域所用的对象。

  • 箭头函数的重要特征箭头函数中没有this和arguments,是真的没有!
  • 箭头函数没有自己的this指向,它会捕获自己定义所处的外层执行环境,并且继承这个this值,指向当前定义时所在的对象。箭头函数的this指向在被定义的时候就确定了,之后永远都不会改变。即使使用call()apply()bind()等方法改变this指向也不可以。

五.构造函数中的this

构造函数中的this是指向实例

function person(name,age,sex){
    this.name = name;
    this.age = age;
    this.sex = sex;
}
let p = new person("hd",18,"boy");
console.log(p.name);//hd
console.log(p.age);//18
console.log(p.sex);//boy

由上可以看出,构造函数中的this指向构造函数下创建的实例

六.原型链中的this

this这个值在一个继承机制中,仍然是指向它原本属于的对象,而不是从原型链上找到它时,它所属于的对象。