Javascript:用状态创建一个函数 [英] Javascript: Creating a function with state

查看:73
本文介绍了Javascript:用状态创建一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个维护状态的javascript函数。这是我提出的一种模式,但我脑子里的一些东西告诉我这是一种反模式。

I want to build a javascript function that maintains state. Here's a pattern that I've come up with, but something in the back of my mind tells me this is an anti-pattern.

function f() { 
    var state = 1;
    f = function() {
        return state++;
    };
    return f();
};

这有什么问题吗?如果是这样,什么是更好的方法?

Is there anything wrong with this? If so, what's a better approach?

推荐答案

嗯,这是最好方式的问题是,但(虽然我知道它有效)我有点不舒服的功能覆盖自己。类似的模式不会这样做,但仍然使用几乎相同的闭包理念是这样的:

Well it's a matter of opinion what the best way is, but (although I know it works) I'm a little uncomfortable with having the function overwrite itself. A similar pattern that doesn't do that but still uses practically the same closure idea is this:

var f = function() {
           var state = 1;
           return function() {
              return state++;
           };
        }();

或者这是另一种方式:

function f() {
   return f.state++;
}
f.state = 1;

当然使用 f.state 方法优点缺点(取决于您的需要)是 .state 属性可以被其他代码读取和修改。

Of course with the f.state method the advantage and disadvantage (depending on your needs) is that the .state property can be read and modified by other code.

这篇关于Javascript:用状态创建一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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