row1
row1

Reputation: 5578

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.

Upvotes: 5

Views: 392

Answers (2)

zzzzBov
zzzzBov

Reputation: 179046

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

Upvotes: 10

Timothy Jones
Timothy Jones

Reputation: 22125

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.

Upvotes: 1

Related Questions