JavaScript - run once without booleans

后端 未结 9 1176
一个人的身影
一个人的身影 2021-01-30 17:42

Is there a way to run a piece of JavaScript code only ONCE, without using boolean flag variables to remember whether it has already been ran or not?

Spe

9条回答
  •  盖世英雄少女心
    2021-01-30 18:06

    An alternative way that overwrites a function when executed so it will be executed only once.

    function useThisFunctionOnce(){
       // overwrite this function, so it will be executed only once
       useThisFunctionOnce = Function("");
       // real code below
       alert("Hi!");
    }
    
    // displays "Hi!"
    useThisFunctionOnce();
    // does nothing
    useThisFunctionOnce();
    

    'Useful' example:

    var preferences = {};
    function read_preferences(){
       // read preferences once
       read_preferences = Function("");
       // load preferences from storage and save it in 'preferences'
    }
    function readPreference(pref_name){
        read_prefences();
        return preferences.hasOwnProperty(pref_name) ? preferences[pref_name] : '';
    }
    if(readPreference('like_javascript') != 'yes'){
       alert("What's wrong wth you?!");
    }
    alert(readPreference('is_stupid') ? "Stupid!" : ":)");
    

    Edit: as CMS pointed out, just overwriting the old function with function(){} will create a closure in which old variables still exist. To work around that problem, function(){} is replaced by Function(""). This will create an empty function in the global scope, avoiding a closure.

提交回复
热议问题