添加面向对象风格——包装对象
- // 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
网友评论