If I execute the following:
var scopes = [];
scopes.push(this);
var x = "123";
function foo() {}
(function () {
var y = "456";
function bar() {}
scopes.push(this);
})();
then the scopes object contains two identical copies of the global object, and both foo() and x are defined as properties of the global object.
But y and bar() are defined in a local scope. Is there any way to obtain a reference to this scope object? If not, is there any 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 the name equal to the contents of obj.name and the value equal to the contents of obj.value, assuming the variable obj is visible in that scope.
Is this possible?
edit: Use case follows --
function define_in(scope, name, value)
{
scope[name] = value;
}
(function() {
define_in(?????, 'x', "super");
var y = x + " powered"; // would like to get "super powered"
})();
There's no "local scope" variable. You'd need make one yourself, unfortunately.
(function () {
var scope = {};
scope.y = "456";
scope.bar = function(){};
scopes.push(scope);
})();
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