Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Just when I think I finally understand Javascript scope

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?

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

new MyFunc();
like image 909
morgancodes Avatar asked Mar 16 '09 22:03

morgancodes


People also ask

What is the scope of JavaScript?

Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript. The two types of scope are local and global: Global variables are those declared outside of a block. Local variables are those declared inside of a block.

When a scope is created JavaScript?

In JavaScript, scopes are created by code blocks, functions, modules. While const and let variables are scoped by code blocks, functions or modules, var variables are scoped only by functions or modules. Scopes can be nested. Inside an inner scope you can access the variables of an outer scope.


2 Answers

In JavaScript, this represents the context object on which the function was called, not the scope in which it was defined (or the scope in which it was called). For MyFunc, this references the new object being created; but for innerFunc, it references the global object, since no context is specified when innerFunc is called.

This tends to trip up those used to Java or similar OO languages, where this almost always references an instance of the class on which the method being called is defined. Just remember: JavaScript doesn't have methods. Or classes. Just objects and functions.

See also: What is the rationale for the behavior of the ‘this’ keyword in JavaScript?

like image 61
Shog9 Avatar answered Sep 23 '22 02:09

Shog9


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.

like image 29
Rakesh Pai Avatar answered Sep 20 '22 02:09

Rakesh Pai