JavaScript closures are a feature of active development and passive development. That is to say, on the one hand, JS has closures to better solve some problems. On the other hand, in order to solve certain problems, JS has to use closures to solve problems barely.
The former is not discussed here. If JS closures can better solve the problem, of course, using closures is better.
What I'm discussing is the latter because of the limitations of JS itself, and the problem that has to be solved with closures, such as the requirement of "variables are only initialized once".
The conventional language solves this:
The code copy is as follows:
class Class{
function init(){
this.n = 0;
}
function func(){
this.n ++;
return this.n;
}
}
var obj = new Class();
JavaScript is generally solved in this way (using closures):
The code copy is as follows:
var obj = {
func : (function(){
var n = 0;
return function(){
n ++;
return n;
}
})()
}
But I would recommend this method (eliminating closures):
The code copy is as follows:
function Class(){
var self = this;
self.n = 0;
self.func = function(){
self.n ++;
return self.n;
}
}
var obj = new Class();
Because the latter is more scalable. When you need to implement different operations on a variable, the latter can just define a different function (that is, simple linear expansion), while the former (closure) needs to be completely rewrite (this is why you often hear the word refactoring).