javascript - How to implement static variables in js
天蓬老师
天蓬老师 2017-06-26 10:58:14
0
5
844
<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

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(5)
某草草

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;
洪涛

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++);
});
过去多啦不再A梦

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

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

var i = 0;
大家讲道理

Don’t use let?

黄舟

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)
    }
})()
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template