返回函数JavaScript函数

    技术2022-07-11  156

    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.

    几周前,我发推文说我喜欢返回函数的函数。 我收到了很多回复…… WTF? 人们了解返回函数的函数的价值很重要; 使用这种技术可以节省您的代码,JavaScript效率以及对JavaScript强大程度的了解。 我已经创建了一个简单的示例,希望向您展示,以便您可以了解我正在尝试交流的想法。

    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:

    假设您有一个带有两个子对象的宿主对象,两个子对象都具有get方法,并且两者执行的任务完全相同 ,但属性不同:

    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:

    这样做好很多,但仍然不理想,因为每次调用该方法时,都会执行一个额外的中间函数。 最好的方法是返回最终函数的函数-这样可以避免每次调用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.

    您在上面看到的是一个返回函数的函数; 每个方法都有自己的获取属性的方法,每个get调用都没有开销。

    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

    Processed: 0.010, SQL: 9