Returns the JavaScript function of the function.
A few weeks ago, I posted a microblog saying that I like to return functions. A few replies soon appeared, basically all of them .... What ?! For a programmer, understanding the function of returning a function is a very important skill. Using it can save a lot of code, make JavaScript more efficient, and further understand the strength of JavaScript. Below are a few simple examples I have written. I hope that you can understand what I mean through it.
Assume that you have an object that contains two sub-objects, both of which have the 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'; } }};
Duplicate code is not a good phenomenon, so we need to create an external function and accept an attribute 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 final required function -- this can eliminate unnecessary function execution:
Function generateGetMethod (attr) {return function () {return typeof this. getAttribute (attr )! = 'Undefined' ;};} var accessors = {sortable: {get: generateGetMethod ('sortable')}, droppable: {get: generateGetMethod ('dropable ')}}; /* It is exactly the same as 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 the function; each sub-object has its own get method, but removes the excess nested function execution process.
This is a very useful technology that can help you eliminate repeated similar code. if used properly, it can make your code more readable and easier to maintain!
Do you understand this?