Simlofi
Simlofi

Reputation: 95

How Javascript functions run

I am wondering how javascript functions load or run.

Take for example i have got these block of javascripts functions;

<span id=indicator></span>

function BlockOne(){
    var textToWrite = document.createTextNode("I am   ");
    document.getElementById("indicator").appendChild(textToWrite);
} 
//==========
function BlockTwo(){
    var textToWrite = document.createTextNode("Going   ");
    document.getElementById("indicator").appendChild(textToWrite);
} 
//=========
function BlockThree(){
    var textToWrite = document.createTextNode("To School   ");
    document.getElementById("indicator").appendChild(textToWrite);
} 

function RunAll(){
    BlockOne();
    BlockTwo();
    BlockThree();
}
window.onload=RunAll();

Please which of these block of function run first or in what order are they going to run.

Upvotes: 0

Views: 78

Answers (1)

Pointy
Pointy

Reputation: 413996

This:

window.onload=BlockOne=BlockTwo=BlockThree;

will result in only "BlockThree" running when the "load" event fires. The way that assignment statement is interpreted is as if it were written:

window.onload = (BlockOne = (BlockTwo = BlockThree));

The right-most = operator causes the symbol "BlockTwo" to be set to the same value as "BlockThree", and then the middle = assigns that value (still "BlockThree") to "BlockOne". Function definition statements bind the function name to a local symbol, but they're not special symbols; they're pretty much the same as ordinary var symbols.

When that's all done, the "onload" property of window is set to just one function reference, and that's "BlockThree". After that point the original functions associated with "BlockOne" and "BlockTwo" will no longer be referenceable; they're essentially gone.

The second will run none of them, because your "RunAll" function is missing the function call operator ( () ) for all three of the functions. If it were

function RunAll(){
  BlockOne();BlockTwo();BlockThree();
}

then all three would run, in the order listed left-to-right.

Upvotes: 6

Related Questions