Reputation: 2052
I am trying to create a predefined private variable inside a function dynamically. The concept I am using, is function return from within a closure block Like this:-
var bar = (function (){
var foo = "Hello World";
return function () {
console.log(foo);
}
}());
bar();
This is the code that i am using to create an equivalent dynamic expression of the above execution
var createClosure = function(fn) {
var __fn = function () {
var foo = "Hello World";
return fn;
}
return __fn();
}
var bar = createClosure(function () {
console.log(foo);
});
bar();
but running the above code gives me ReferenceError: foo is not defined
What should be the equivalent representation of a function return from a closure block?
Upvotes: 0
Views: 55
Reputation: 2052
Here is an way out that I have found, let me know, if this is the correct approach.
var createClosure = function(fn) {
var __fn = function () {
var foo = "Hello World";
var entire = fn.toString();
var body = entire.substring(entire.indexOf("{") + 1, entire.lastIndexOf("}"));
return function () {
eval(body);
}
}
return __fn();
}
var bar = createClosure(function () {
console.log(foo);
});
bar();
Upvotes: -1
Reputation: 2526
This is as close as you can get:
function createClosure(fn) {
const baz = {};
baz.foo = "Hello World";
return () => fn(baz);
}
const bar = createClosure(baz => console.log(baz.foo));
bar();
Or just pass in foo
as an argument directly. But you can not just make foo
exist in another scope. So you could obviously make it global but that wouldn't be a good idea either.
Upvotes: 2