Just when I think I finally understand Javascript scope

前端 未结 4 690
傲寒
傲寒 2021-01-01 02:21

I run in to something that illustrates how I clearly don\'t get it yet.

Can anyone please explain why the value of \"this\" changes in the following?



        
4条回答
  •  生来不讨喜
    2021-01-01 03:12

    Just do the following:

    var MyFunc = function(){
        var self = this;
        alert(self);
        var innerFunc = function(){
            alert(self);
        }
        innerFunc();
    };
    
    new MyFunc();
    

    This way self will always mean this, irrespective of where you're calling it from, which is usually what you want.

提交回复
热议问题