Why window.addEventListener does not work?

This question already has an answer here:

  • var functionName = function() {} vs function functionName() {} 31 answers

  • While you using var x = function(){} to declare functions, it should be declare before you call the function.

    By function x (){} , x will exist in current scope, no matter how later it declare. Because such side effect , the var x = function(){} are more recommended. For example:

    var user = 'alien';
    if( user == 'alien') {
        function salute () { console.log("Welcome to Earth!"); }
    } else {
        function salute (){ console.log("Good day!"); }
    }
    

    The salute() will print Good day! anyway, even though it not we want at all.


    Declare the function before.

    var initialiseTable = function () {
        console.log("hello world!!");
    };
    try {
        window.addEventListener("load", initialiseTable, false);
    } catch(e) {
        window.onload = initialiseTable;
    }
    

    For more information about declaring a function read this: var functionName = function() {} vs function functionName() {}


    Since you come from C#, the difference is a lot like:

    class A {
        public int method2() {
            //I can call method1 even though it *declared* later below
            int a = method1(); 
        }
    
        public int method1() {
    
        }
    }
    

    vs

    class B {
        public int method2() {
            bool a = method1(3); //I can't call it because it is *assigned* later below.
                             //In fact I cannot even compile it 
            Func<int, bool> method1 = x => x == 3;
        }
    }
    

    You may notice the difference in javascript, if you look at:

    function a() {
    
    }
    

    There is no assignment anywhere.

    Where as with var a = function(){} there is obviously assignment and it is similar to the latter C# example.

    链接地址: http://www.djcxy.com/p/2838.html

    上一篇: 使用命名函数表达式有什么意义?

    下一篇: 为什么window.addEventListener不起作用?