开发者

Calling JS functions assigned to variables

开发者 https://www.devze.com 2023-01-13 08:24 出处:网络
Some time ago I asked a question about the same issue, @BenAlabaster explained it thoroughly in his answer, I guess I am still missing a piece of logic here.

Some time ago I asked a question about the same issue, @BenAlabaster explained it thoroughly in his answer, I guess I am still missing a piece of logic here.

开发者_运维百科

I tried to call functions that are assigned to variables like I've shown below, in the last function. Well it didn't work. Assuming it happened because the variable functionThree is outside the addOnload() function, I tried to move it inside and the browser just crashed.

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!");
}


There is a slight issue with your addOnloadFunction: it should be:

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

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


This happens because you use functionThree before it is defined.

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
}

Apart from that, your implementation of addOnload() should go something like this:

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);
}   
0

精彩评论

暂无评论...
验证码 换一张
取 消