调用分配给变量的JS函数

时间:2010-08-29 21:15:46

标签: javascript

前段时间我问了一个关于同一问题的问题,@ BenAlabaster彻底解释了in his answer,我想我在这里仍然缺少一条逻辑。

我试着在最后一个函数中调用分配给变量的函数,如下所示。 好吧它没用。假设它发生是因为变量functionThreeaddOnload()函数之外,我试图将其移到里面,浏览器就崩溃了。

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 个答案:

答案 0 :(得分:3)

这是因为您在定义之前使用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);
}   

答案 1 :(得分:3)

addOnloadFunction存在轻微问题:它应该是:

function addOnload(newFunction){
    var oldOnload = window.onload;

    if(typeof oldOnload == "function"){
        window.onload = function(){
            newFunction();
            oldOnload();
        }
    }
    else{
        window.onload = newFunction;
    }
}