亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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

天蓬老師
天蓬老師

歡迎選擇我的課程,讓我們一起見證您的進(jìn)步~~

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夢(mèng)

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