Вопрос

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 variable has not anything to do with Scope, in terms of how ECMAscript implements Lexical scoping underneath.

this will 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.

var myScope = { };  // respectively Object.create( null );

In strict mode, the implementation will just set this to undefined for any function which got invocated as is. That means, the value of this is decided of how a function gets called. In your case, its a self-executing function and hence, its this will always be undefined in strict mode and window (global) in non strict mode.

Другие советы

myVar is scoped to the containing closure. When I run your code, and then run $.myFunc(), the output is undefined 1, since myVar is still present in that closure. There is, however, no way to access myVar from outside of the closure. That is the same mechanism used to implement private variables in JS.

What @jAndy is saying is also true, this is unrelated to scope, and in this case the this of the anonymous function is undefined

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top