Executing an inner function by returning the function name
I would开发者_运维百科 like to execute the inner function but I am struggling to understand why it comes back as not defined
object.method2();
var object = {
method1 : function(){
return function(){
innerFunction();
}
},
method2 : function(){
function innerFunction(){
alert('I am showing as not defined but I want to be executed')
}
executeInnerFunction = object.method1()
executeInnerFunction();
}
}
JavaScript has lexical scoping---code can only see variables declared in its scope (function) or any ancestor scope up the syntax tree. Since innerFunction
is declared in the scope of method2
, and method2
is syntactically not an ancestor of method1
, you can't use it.
innerFunction is only known in method2 since it is declared in the scope of method2.
If you want to have access from method1, you may declare innerFunction over this :
this.innnerFunction = function(){}
, so that object.innerFunction()
can be called.
If you do not want to expose innerFunction as a public method of object you may want to use closure :
function doObject(){
function innerFunction(){alert('yihou');}
return {
method1:function(){innerFunction();},
method2:function(){}
};
}
Your assignment also isn't right, I think. Do this instead:
executeInnerFunction = object.method1;
You want to store a reference to the method, not the results of calling the method once.
Beyond that, see what ngn had to say.
Others have answered the scope issue, but you are also trying to call object.method2()
before it exists.
Function declarations are processed before code is executed so you can call declared functions higher up the code than where they are written, however object.method2 is created by assignment, so object doesn't have a method2 property until the assignement code is executed, which is after the call.
精彩评论