代码之家  ›  专栏  ›  技术社区  ›  Dean

调用分配给变量的JS函数

  •  1
  • Dean  · 技术社区  · 14 年前

    不久前我问了一个关于同一问题的问题,@BenAlabaster解释得很透彻 in his answer ,我想我还是缺少一点逻辑。

    但没用。假设这是因为变量 functionThree 在外面 addOnload() 函数,我试着把它移到里面,浏览器就崩溃了。

    addOnload(functionOne);
    addOnload(functionTwo);
    addOnload(functionThree);
    
    function addOnload(newFunction){
        oldOnload = window.onload;
    
        if(typeof oldOnload == "function"){
            window.onload = function(){
                if(oldOnload){
                    oldOnload();
                }
                    newFunction();    //This is what I missed, and that's what caused the crash. 
            }
        }
        else{
            window.onload = newFunction;
        }
    }   
    
    function functionOne(){
        alert("This is the first function on this page!");
    }
    
    function functionTwo(){
        alert("This is the second function on this page!");
    }
    
    functionThree = function(){
        alert("This is the third function on this page!");
    }
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Maurice Perry    14 年前

    function addOnload(newFunction){
        var oldOnload = window.onload;
    
        if(typeof oldOnload == "function"){
            window.onload = function(){
                newFunction();
                oldOnload();
            }
        }
        else{
            window.onload = newFunction;
        }
    }   
    
        2
  •  3
  •   Tomalak    14 年前

    这是因为你使用 functionThree 在它被定义之前。

    function x() { 
      // a function that can be used before its declaring block
    }
    
    x = function() {
      // a variable that gets assigned a function object when the execution
      // of the program reaches this point, but not before
    }
    

    除此之外,你的 addOnload()

    function addOnload(newFunction){
      if (typeof window.onloadFunctions === "undefined") {
        window.onloadFunctions = [];
        window.onloadFunctions.push(window.onload);
    
        window.onload = function() {
          for(var i=0; i<window.onloadFunctions.length; i++) {
            var f = window.onloadFunctions[i];
            if (typeof f === "function") f();
          }
        }
      }
      window.onloadFunctions.push(newFunction);
    }