彻底搞懂js中this指向问题

this指向的总结

浏览器环境
在全局的作用域中,this指向的是window对象

console.log(this);   //window对象
console.log(this === window);  //true

一、ES5中this的指向

1.非严格模式:函数中的this指向window对象,fn函数为window的一个属性,运行fn时,fn函数中的this指向window,根本上来说就是this指向函数运行时的环境

var fn = function(){
    console.log(this);
    console.log(this === window);   
}
fn();

//window对象
//true

2.严格模式:如果使用window调用函数的话,this指向undefined,使用window调用函数的话,指向window对象

 'use strict'
fn = function () {
    console.log(this);
    console.log(this === window)
}
fn();
//undfined
//false
window.fn();
//Window对象
//true

但是如果是在定时器中的this,无论是否被window调用,this都指向window。

'use struct'
var fn = function () {
    setTimeout(functioin(){
        console.log(this);
        console.log(this === window);
    },500)
}
fn();
//Window对象
//true

二、ES6中箭头函数的this指向

箭头函数中this的指向取决于定义时环境中的this指向一致。

var fun = () => {
    console.log(this);
    console.log(this === window);
}
fun();
//Window对象
//true
//定义箭头函数时,过程:()=>{...}所在的环境是window,所以运行fun()时,箭头函数内部的this指向window

var obj = {
    name:'Jay',
    age:25,
    fn:()=>{console.log(this)},
    fun:function(){
        console.log(this)
    }
};
//在定义fn时,fn内部this的指向就是定义obj对象时所在的环境,obj所在的环境是window,所以调用obj.fn()时,返回的this就是Window对象
obj.fn(); //Window对象
obj.fun();//{name: "Jay", age: 25, fn: ƒ, fun: ƒ}

var name = 'Milaoshu';
var obj = {
    name:'Jay',
    age:25,
    fn1:function(){
        return function(){
            console.log(this.name);
        }
    },
    fn2:() =>{
        return () => {
            console.log(this.name);
        }
    }
};
var fnn1 = obj.fn1();
var fnn2 = obj.fn2();
fnn1();//Milaoshu
fnn2();//Milaoshu

三、在dom中事件处理函数的this指向时触发该事件的对象,构造函数中this的指向为通过构造函数所创建出的对象实例。

function Person (){
    this.name = 'Tom',
    this.age = 25;
    console.log(this);
}
var p1 = new Person();
//Person {name: "Tom", age: 25}

发布了33 篇原创文章 · 获赞 70 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42878211/article/details/105423541