[removed] How is “function onload() {}” different from “onload = function() {}”?

前端 未结 6 613
慢半拍i
慢半拍i 2021-02-02 11:37

In the answers to this question, we read that function f() {} defines the name locally, while [var] f = function() {} defines it globally. That makes p

6条回答
  •  日久生厌
    2021-02-02 12:14

    This two snippets declares a function in the current scope, named "onload". No binding is done.

    function onload() { ... }
    

    .

    var onload = function() { ... }
    

    This snippet assigns a function to a property/variable/field named "onload" on the current scope:

    onload = function() { ... }
    

    The reason why Firefox performed the binding and raised the onload event on the 1st snippet and the others didn't might be because the Firefox chrome (its user interface) itself is written and automated using JavaScript - that's why it's so flexible and easy to write extensions on it. Somehow, when you declared the locally-scoped onload function that way, Firefox "replaced" the window's (most likely the local context at the time) implementation of onload (at that time, an empty function or undefined), when the other browsers correctly "sandboxed" the declaration into another scope (say, global or something).

提交回复
热议问题