function a(){
alert('A');
a = function(){
alert('B');
};
}
function a(){
alert('A');
return function(){
alert('B');
};
}
This function rewrites itself after being called for the first time, thus avoiding unnecessary repetition of operations every time it is called. How to understand this specifically? Isn’t the function execution thread the same before and after rewriting the function?
For example, different browsers have different API names, and if you want to encapsulate a unified interface, your code will look like this
Differentiates a Boolean state without using extra variables and without using if-else.
For example, some behaviors have different logic in initialized and uninitialized situations, then you can write like this:
The bad thing here is that a global variable is introduced. Then this variable can be encapsulated into an internal state, which can be written like this:
If you use the method mentioned by the questioner:
In addition, this way of writing feels very functional (I don’t know much about functional expressions, so I don’t dare to be absolute). So here is the problem of programming paradigm.
Feel the following three different ways of writing:
Process-oriented:
Object-oriented:
Functional expression:
The functional method has many advantages. You need to understand functional programming for this.
The browser API example upstairs is a good example. Generally speaking, function rewriting is more about avoiding certain unnecessary operations so as to optimize code performance. Let me give you another example. More commonly used:
Simply put
The first time you run a function, alert('A') is executed, and the second time it is executed, alert('B').
It is not so much to avoid repeating unnecessary operations as it is to perform additional operations. When it is run for the first time, it does thing A, and when it runs later, it does thing B.