9.adding OO-style object wrapping (thanks amcournoyer) -- now you can to _(array).each()

添加面向对象风格——包装对象

-  // Create a safe reference to the Underscore object for the functions below.
-  var _ = root._ = {};

  // If Underscore is called as a function, it returns a wrapped object that
  // can be used OO-style. This wrapper holds altered versions of all the 
  // underscore functions.
  var wrapper = function(obj) { this.wrapped = obj; };
  
  // Create a safe reference to the Underscore object for reference below.
  var _ = root._ = function(obj) { return new wrapper(obj); };

  // ...

  // Return a sorted list of the function names available in Underscore.
  _.functions = function() {
    var functions = [];
    for (var key in _) if (Object.prototype.hasOwnProperty.call(_, key)) functions.push(key);
    return _.without(functions, 'VERSION', 'prototype', 'noConflict');
  };

 _.each(_.functions(), function(name) {
    wrapper.prototype[name] = function() {
      Array.prototype.unshift.call(arguments, this.wrapped);
      return _[name].apply(_, arguments);
    };
  });

添加链式调用,每次执行会返回一个新的包装对象

image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容