Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Function Syntax Explanation: function object.myFunction(){..}

I would consider myself to be reasonably competent with JavaScript and familiar with many of the different ways of achieving the same thing. But today I came across some function syntax which I hadn't seen before:

function document.body.onload()
{
    alert('loaded');   
}

If I were to write such code I would have done it like this:

document.body.onload = function()
{
    alert('loaded');   
}

Ignoring the fact that this is not the best way to handle the onload event, is this actually valid JavaScript? It appears to causes syntax errors in FireFox (and JSLint), so I am guessing that it is Internet Explorer only syntax? If it is IE only then I would like to remove it but I am concerned that it might have some quirky side effect.

like image 630
row1 Avatar asked Nov 29 '11 05:11

row1


2 Answers

function document.body.onload is non-standard JavaScript syntax. Use the second format, and fire whomever wrote the original code.

Don't forget the semi-colon after the end }
document.body.onload = function () {
    ...code...
}; //this is easy to miss
like image 120
zzzzBov Avatar answered Sep 28 '22 02:09

zzzzBov


No, it's not valid. the function X() {} variant requires that the name of the function only contains letters, digits, '$' and '_'.

If you want to check other syntax, you can get the standard here, but the syntax diagrams in the back of JavaScript: The Good Parts are much easier to digest.

like image 36
Timothy Jones Avatar answered Sep 28 '22 03:09

Timothy Jones