4

I am new to javascript and have a quick question. Say i have the following code:

function entryPoint()
{
   callFunction(parameter);
}

function callFunction(parameter)
{
   ... //do something here
   var anotherFunction = function () { isRun(true); };
}

My question is that when callFunction(parameter) is called, and the variable anotherFunction is declared, does isRun(true) actually execute during this instantiation? I am thinking it doesnt and the contents of the anotherFunction are only "stored" in the variable to be actually executed line by line when, somewhere down the line, the call anotherFunction() is made. Can anyone please clarify the function confusion?

4

3 に答える 3

5

It seems the confusion is this line of code

var anotherFunction = function () { isRun(true); };

This declares a variable of a function / lambda type. The lambda is declared it is not run. The code inside of it will not execute until you invoke it via the variable

anotherFunction(); // Now it runs
于 2012-04-11T18:00:35.200 に答える
4

You almost described it perfectly.

anotherFunction just receives a reference to a newly created Function Object (yes, Functions are also Objects in this language) but it does not get executed.

You could execute it by calling

anotherFunction();

for instance.

于 2012-04-11T18:00:43.360 に答える
1

You can write a simple test like so:

entryPoint();

function entryPoint()
{
    alert("In entryPoint");
    callFunction();
}

function callFunction()
{
    alert("In callFunction");
    var anotherFunction = function () { isRun(); };
}

function isRun()
{
    alert("In isRun");
}

​ And, the answer is no, isRun() does not get called.

于 2012-04-11T18:07:33.257 に答える