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();
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With