A few weeks ago, I posted a Weibo post saying that I like functions that return functions. A few replies soon appeared, basically all of them...what? ! For a programmer, understanding the function that returns a function is a very important skill. Using it you can save a lot of code, make JavaScript more efficient, and let you further understand the power of JavaScript. Below are a few simple examples I wrote, through which you can understand what I mean.
Suppose you have an object that contains two child objects, and they all have a get method. These two methods are very similar and slightly different:
var accessors = { sortable: { get: function() { return typeof this.getAttribute('sortable') != 'undefined'; } }, droppable: { get: function() { return typeof this.getAttribute('droppable') != 'undefined'; } }};Repeated code is not a good phenomenon, so we need to create an external function and accept a property name:
function getAttribute(attr) { return typeof this.getAttribute(attr) != 'undefined';}var accessors = { sortable: { get: function() { return getAttribute('sortable'); } }, droppable: { get: function() { return getAttribute('droppable'); } }};This is much better, but it is still not perfect because there are still some redundant parts. A better way is to let it directly return the function you need in the end - this will eliminate the redundant function execution:
function generateGetMethod(attr) { return function() { return typeof this.getAttribute(attr) != 'undefined'; };}var accessors = { sortable: { get: generateGetMethod('sortable') }, droppable: { get: generateGetMethod('droppable') }};/* It is completely equivalent to the original method: */var accessors = { sortable: { get: function() { return typeof this.getAttribute('sortable') != 'undefined'; } }, droppable: { get: function() { return typeof this.getAttribute('droppable') != 'undefined'; } }};*/What you see above is a function that returns a function; each child object has its own get method, but the unnecessary function nested execution process is removed.
This is a very useful technique that can help you eliminate duplication of similar code. If used properly, it can make your code more readable and easier to maintain!
Do you understand?