简体   繁体   中英

Can someone explain how this part

The complete code can be found here: http://www.webdeveloper.com/forum/showthread.php?t=224180#6 This emulates jquery like functionality. The next part defines the methods

//define some methods for the utility:
var meths={
    hide:function(a){if(a)a.style.display="none";},
    show:function(a){if(a)a.style.display="";},
    remove:function(a){if(a)a.parentNode.removeChild(a);},
    color:function(a){a.style.color=this||a.style.color;},
    size:function(a){if(a)a.style.fontSize=this||a.style.fontSize;}

};//end meths

I get the above part. This is, of course, a part of a closure. I can't seem to understand the next part and how calling X.hide() calls the corresponding method in X. If someone would take the time to explain this

//bind the methods to the collection array:
for(var meth in meths)
  (function(n,m){
    output[n]=function(x){output.map(m,x); return output;}
  }(meth, meths[meth]));//next method

return output;
// Earlier in the code, 'output' was defined as an array...
var output = [];

// For each key in the object 'meths'...
// (which was defined as an object of methods)
for (var meth in meths)
    // Execute the closure... (using the key as 'n' and the method as 'm')
    (function(n,m){
        // Using the key, assign to the 'output' array a function that
        // maps the current method that we're on, for each element in the array.
        // (Array.map() runs a function, given as the first argument, for each
        // element in an array)
        //
        // In this case, the 'x' in the function is the placeholder for a
        // parameter. Like jQuery, this returns the modified output for chaining.
        output[n] = function(x){ output.map(m,x); return output; };
    })(meth, meths[meth]); // Using the key and method

return output;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM