As I understand, when a variable is defined it gets attached to the ‘closest’ local scope via this.
If no scope is set locally, the closest scope becomes window.
In strict mode, however, the local scope is set to undefined instead of window, as part of the ECMAscript 5 spec designed to limit misuse of the global scope.
Using an immediately invoked function expression pattern and strict mode for creating a jQuery plugin
;( function( $, window ){
"use strict";
var myScope = this;
var myVar = 1;
var myFunction = function(){
console.log( myScope, myVar );
}
$.myFunc = myFunction;
})( jQuery, window );
the local scope (context) isn’t created (via a function call) and thus set to undefined.
If the local scope is undefined and window.myVar is undefined, what is the scope of the variable myVar and how do you access it?
The
this context variablehas not anything to do with Scope, in terms of how ECMAscript implements Lexical scoping underneath.thiswill always reference the object of invocation, which can change during run-time, whereas the scope / context cannot get changed. You got two function invocations there, each of those has its own Execution Context and its own Activation Object respectively Lexical Environment Record, which are used by the implementation to store any local data like formal paramteres, variables and function declarations.What you are actually trying to achieve here, is to create a hash / namespace object which serves as container to hold data. Therefore, you shouldn’t assign
this, but just create your own Object.In strict mode, the implementation will just set
thistoundefinedfor any function which got invocated as is. That means, the value ofthisis decided of how a function gets called. In your case, its a self-executing function and hence, itsthiswill always beundefinedin strict mode andwindow(global) in non strict mode.