有人可以解释这部分是怎么回事

时间:2012-02-08 06:13:16

标签: javascript

完整的代码可以在这里找到:http://www.webdeveloper.com/forum/showthread.php?t=224180#6这模仿jquery之类的功能。下一部分定义方法

//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

我得到了上述部分。当然,这是关闭的一部分。我似乎无法理解下一部分以及调用X.hide()如何调用X中的相应方法。如果有人花时间解释这个

//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;

1 个答案:

答案 0 :(得分:2)

// 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;