Javascript / ECMAscript / Spidermonkey: volume versus this?

If I do the following:

var scopes = [];
scopes.push(this);
var x = "123";
function foo() {}

(function () {
   var y = "456";
   function bar() {}
   scopes.push(this);
})();

      

the object scopes

contains two identical copies of the global object, and both foo()

and x

are defined as properties of the global object.

But y

also bar()

defined in the local area. Is there a way to get a reference to this scope object? If not, is there a way to define an object programmatically within that scope?

for example in the global scope I can do this:

this.wham = "789";
this.baz = function() { return 2; }
var vname = 's';
this[vname] = "Dynamic name!"

      

and I can access them via wham

and baz()

and s

.

If I had an object like this:

var obj = {name: 'ha', value: 3};

      

I'm looking for a way to define a variable in a local scope that has a name equal to content obj.name

and a value equal to content obj.value

, provided that the variable obj

is visible in that scope.

Is it possible?

Edit: Use case -

function define_in(scope, name, value)
{
    scope[name] = value;
}

(function() {
   define_in(?????, 'x', "super");
   var y = x + " powered";  // would like to get "super powered"
})();

      

+3


source to share


2 answers


There is no "local scope" variable. You have to do it yourself unfortunately.



(function () {
   var scope = {};
   scope.y = "456";
   scope.bar = function(){};
   scopes.push(scope);
})();

      

+2


source


Instead of using the self executing function, you can create a function constructor and define object members and / or private members, which will allow you to choose what to show and what not if that's what you are looking for.



0


source







All Articles