Is there any way to introduce the local variable “iWantThisHere” here, so i can call obj.n()
var obj = {
test: "sure",
n : function(){ console.log(iWantThisHere); }
};
i tried with:
function fake(methods){
var F = new Function('methods', "var iWantThisHere = 'u have it', obj = {}; for( var meth in methods){ obj[meth] = methods[meth] } return obj;");
return F(methods); }
console.log(fake(obj), fake(obj).n());
i dont want to use globals here. Imagine a modul system where each modul uses for example a util class, which is defined for example in a App object. So i always have to type for eg App.utils.map or something like that. It would be nice to have a shortcut to this util function which is a local variable in the modul context itself.
EDIT
— theres no way to do that —-
Introduce a closure:
Demo:
This is the most common (dare I say recommended) way to do javascript programming, by creating functions to restrict variables to a scope. It is necessary because javascript does not have block-level scoping.