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

倾然丶 夕夏残阳落幕 提交于 2019-12-17 20:58:19

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/8306445/javascript-function-syntax-explanation-function-object-myfunction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!