A few weeks back, I tweeted that I loved functions that returned functions. I got quite a few replies to the tune of....WTF?! It's important that people understand the value of functions that return functions; using this technique can save you code, JavaScript efficiency, and a gained understanding of how powerful JavaScript can be. I've created a quick example I'd like to show you so that you can get the idea I was trying to communicate.
Let's say you have one host object with two child objects, both with get
methods, and both do exactly the same task but with a different attribute:
var accessors = { sortable: { get: function() { return typeof this.getAttribute('sortable') != 'undefined'; } }, droppable: { get: function() { return typeof this.getAttribute('droppable') != 'undefined'; } } };
Repeating the same code isn't ideal, so we could create one external function, passing it an attribute argument:
function getAttribute(attr) { return typeof this.getAttribute(attr) != 'undefined'; } var accessors = { sortable: { get: function() { return getAttribute('sortable'); } }, droppable: { get: function() { return getAttribute('droppable'); } } };
That's a lot better but still not ideal because there's an extra, intermediate function execution every time the method is called. What would work best is a function that returned the final function -- that would eliminate the extra function execution with every call to get:
function generateGetMethod(attr) { return function() { return typeof this.getAttribute(attr) != 'undefined'; }; } var accessors = { sortable: { get: generateGetMethod('sortable') }, droppable: { get: generateGetMethod('droppable') } }; /* functional equivalent to the original code: 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 returning a function; each method gets its own method for getting the property and there's no overhead upon each get
call.
This is a really useful technique that saves you from repeating likewise code and, when used correctly, is easy to understand and maintain!
原文链接:https://davidwalsh.name/javascript-functions