js中this的指向比较绕,和其他语言可能有所不一样,看很多资料举的例子也很绕,这里自己做一下记录,方便牢记:

let a={
    a:1,
    check:function(){
        //这里的this指向的是该对象a的;
        console.log('check:',this);

        //匿名函数function() 会把this提升的指向window
        let b=function(){
            console.log('b:',this)
        };
        b();

        //这里是ec最新的箭头函数,箭头函数是没有this的,这里的this是外层传进来的this,也就是check函数的this;
        let c=()=>{
            console.log('c:',this)
        };
        c();
    }
};

function outfun(){
    console.log('outfun:',this);
}

//调用函数
a.check();
outfun();

//结果
check: {a: 1, check: ƒ}
b: Window {0: global, window: Window, self: Window, document: document, name: '', location: Location, …}
c: {a: 1, check: ƒ}
outfun: Window {0: global, window: Window, self: Window, document: document, name: '', location: Location, …}

说明:

1.function()函数的this指向的是外层this,这个具体要看外层是什么,如果是对象内则可能是整个对象,如果是全局函数则可能是window。
2.匿名函数this的指向是window或者undifined(typescript 严格模式)


曾经的少年
9 声望0 粉丝

擅长PHP,mysql,熟悉HTML、CSS、JavaScript能做网站,了解react、typescript能上手,