search

Home  >  Q&A  >  body text

javascript - How to implement static variables in js

<button type="button" onclick="func();">按钮</button>

var i = 0;
func(){
    i += 1;
    console.log(i)
}

Requirement: Click the button variable to increase by 1. Find the best way to achieve it.
To add, there are many ways to implement it.

  1. Save directly into global variables - polluting the global namespace

  2. Use a global array to save the global variables of the current app - does not conform to the current architecture

  3. Closure - does not seem to adapt to the current scene (use onclick to trigger the function)

  4. Docked into html elements - still very low

  5. Using a large anonymous function to extend the life cycle of a variable - does not comply with the current architecture

天蓬老师天蓬老师2716 days ago825

reply all(5)I'll reply

  • 某草草

    某草草2017-06-26 11:00:14

    Who said closures don’t apply?

    var func = (function(){
    var i = 0;
    return function(){
        i++;
        console.log(i);
    }
    
    }());

    Or you can do this:

    var func = function(){
        func.i++;
        console.log(func.i);
    };
    func.i = 0;

    reply
    0
  • PHP中文网

    PHP中文网2017-06-26 11:00:14

    Saved in dom node attributes

    <button data-click-number="0" type="button" id="incBtn" >按钮</button>
    $("#incBtn").on('click',function(){
     var preClickNumber=$(this).attr('data-click-number') ?: 1;
     $(this).attr('data-click-number',preClickNumber++);
    });

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-26 11:00:14

    js has no static variables. There are only local variables and global variables.

    <button type="button" onclick="++i">按钮</button>
    
    var i = 0;

    reply
    0
  • 大家讲道理

    大家讲道理2017-06-26 11:00:14

    Don’t use let?

    reply
    0
  • 黄舟

    黄舟2017-06-26 11:00:14

    Closures are very popular. I suggest you read some books on functional expressions of JavaScript. This is also a major feature of JavaScript

    let click = (() => {
        var i = 0;
        return function() {
          i += 1;
          console.log(i)
        }
    })()

    reply
    0
  • Cancelreply