<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.
Save directly into global variables - polluting the global namespace
Use a global array to save the global variables of the current app - does not conform to the current architecture
Closure - does not seem to adapt to the current scene (use onclick to trigger the function)
Docked into html elements - still very low
Using a large anonymous function to extend the life cycle of a variable - does not comply with the current architecture
Who said closures don’t apply?
Or you can do this:
Saved in dom node attributes
js has no static variables. There are only local variables and global variables.
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