javascript中的函数只能调用一次

javascript中的函数只能调用一次

本文介绍了javascript中的函数只能调用一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个只能执行一次的函数,在第一次执行后不会被执行。我从C ++和Java中知道可以做这些工作的静态变量,但是我想知道是否有更优雅的方法来实现?

I need to create a function which can be executed only once, in each time after the first it won't be executed. I know from C++ and Java about static variables that can do the work but I would like to know if there is a more elegant way to do this?

推荐答案

如果通过不执行,您的意思是多次调用时不会做任何事情,您可以创建一个关闭:

If by "won't be executed" you mean "will do nothing when called more than once", you can create a closure:

var something = (function() {
    var executed = false;
    return function () {
        if (!executed) {
            executed = true;
            // do something
        }
    };
})();

在回答@Vladloffe(现已删除)的评论时:使用全局变量,其他代码可能重置执行标志的值(您为其选择的任何名称)。关闭,其他代码无法做到这一点,无意中或故意。

In answer to the comment by @Vladloffe (now deleted): With a global variable, other code could reset the value of the "executed" flag (whatever name you pick for it). With a closure, other code has no way to do that, either accidentally or deliberately.

这篇关于javascript中的函数只能调用一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:58