Home  >  Article  >  Web Front-end  >  Introduction to the general method of eliminating closures in JavaScript_javascript tips

Introduction to the general method of eliminating closures in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:09:061606browse

JavaScript’s closure is a feature that it actively develops, and it is also a feature that develops passively. In other words, on the one hand, JS can better solve some problems with closures. On the other hand, in order to solve certain problems, JS problem, and had to use closures to barely solve the problem.

The former will not be discussed here. If JS closures can solve the problem better, of course it is better to use closures.

What I am discussing is the latter, because of the limitations of JS itself, which have to be solved with closures, such as the requirement of "variables are only initialized once".

The conventional language is solved like this:

Copy code The code is as follows:

class Class{
function init(){
This.n = 0;
}
function func(){
This.n ;
Return this.n;
}
}
var obj = new Class();

JavaScript usually solves this problem (using closures):

Copy code The code is as follows:

var obj = {
func : (function(){
var n = 0;
return function(){
n ;
Return n;
}
})()
}

But I prefer this method (eliminating closures):

Copy code The code 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 has better scalability. 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) will need to be completely rewritten (which is why you often hear the word refactoring).

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn