function mainFunc(){
function f1(){
alert("f1");
}
function f2(){
alert("f2");
}
}
function myFun(){
var data = f1();
}
Is there any possibilities to call the f1() function from outside of the closure in javascript.
function mainFunc(){
function f1(){
alert("f1");
}
function f2(){
alert("f2");
}
}
function myFun(){
var data = f1();
}
Is there any possibilities to call the f1() function from outside of the closure in javascript.
If you create an object using mainFunc
you can access the methods inside.
function mainFunc(){
this.f1 = function (){
alert("f1");
}
this.f2 = function(){
alert("f2");
}
}
function myFun(){
var mainObj = new mainFunc();
var data = mainObj.f1();
}
myFun();
Try returning an object that can still access the function defined in mainFunc
's closure!
A little messy, but hope it helps:
function mainFunc(){
function f1(){
alert("f1");
}
function f2(){
alert("f2");
}
return {
f1 : f1,
f2 : f2
};
}
function myFun(){
var data = mainFunc().f1();
}
The idea behind closures is protection while providing access to values in the closure's scope.
Check out previous threads if you haven't already.
I'm fond of this epic answer:
How do JavaScript closures work?
Try This.
var mainFunc = new mainFunc();
function mainFunc(){
this.f1 = f1;
this.f2 = f2;
function f1(){
alert("f1");
}
function f2(){
alert("f2");
}
}
function myFun(){
var data = mainFunc.f1();
}
You basically have to pass the function out or make it accessible some way
There are numerous ways you can do this.
Here is an example of using a callback function. So passing in a function as a parameter to mainFunc
. The function you pass in is itself expecting two functions f1
anf f2
to be passed to it.
function mainFunc(cb){
var f1 = function(){
console.log("f1");
}
var f2 = function(){
console.log("f2");
}
cb(f1, f2);
}
//this example uses an anonymous function as a callback
mainFunc(function(fnA, fnB){
fnA();
fnB();
})
//this example uses your named function myFun as a callback
function myFun(fnA, fnB){
fnA();
fnB();
}
mainFunc(myFun);
Try utilizing Function.prototype.toString()
, Function
function mainFunc(){
function f1(){
alert("f1");
}
function f2(){
alert("f2");
}
}
function myFun(){
var f1 = "";
var res = mainFunc.toString().split("\n");
for (var i = 0; i < res.length; i++) {
if (res[i].indexOf("f1") !== -1) {
f1 += res[i].trim();
}
if (res[i].indexOf("}") !== -1
&& res[i -1].indexOf("f1") !== -1) {
f1 += res[i].trim();
}
};
f1 = new Function("(" + f1 + "())");
f1();
}
myFun();