JavaScript-不带布尔值运行一次 [英] JavaScript - run once without booleans

查看:59
本文介绍了JavaScript-不带布尔值运行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以只运行 ONCE 一段JavaScript代码,而无需使用布尔标志变量来记住它是否已经运行?

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?

具体不是类似

var alreadyRan = false;
function runOnce() {
  if (alreadyRan) {
    return;
  }
  alreadyRan = true;

  /* do stuff here */

}

我将有很多这类函数,并且保留所有布尔值会很杂乱...

I'm going to have a lot of these types of functions and keeping all booleans would be messy...

推荐答案

一种替代方法,该方法在执行时会覆盖函数,因此只能执行一次.

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();

有用的"示例:

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


如CMS所指出的那样,仅用function(){}覆盖旧函数将创建一个闭包,其中旧变量仍然存在.要变通解决此问题,将function(){}替换为Function("").这将在全局范围内创建一个空函数,避免关闭.


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.

这篇关于JavaScript-不带布尔值运行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆