-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
如何手写一个自己的工具库 #16
Comments
环境检测,window(web worker)=>global=>node vm=>小程序 var root = (typeof self == 'object' && self.self == self && self) ||
(typeof global == 'object' && global.global == global && global) ||
this ||
{}; |
支持函数式和面向对象调用方式 // 函数式风格
_.each([1, 2, 3], function(item){
console.log(item)
});
// 面向对象风格
_([1, 2, 3]).each(function(item){
console.log(item)
}); 方式如下 var _ = function(obj) {
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
_.mixin = function(obj) {
_.each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return func.apply(_, args);
};
});
return _;
};
_.mixin(_); |
支持模块化导出 if (typeof exports != 'undefined' && !exports.nodeType) {
if (typeof module != 'undefined' && !module.nodeType && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
} |
链式调用 _.chain([1, 2, 3, 4])
.filter(function(num) { return num % 2 == 0; })
.map(function(num) { return num * num })
.value(); // [4, 16] _.chain = function (obj) {
var instance = _(obj);
instance._chain = true;
return instance;
};
var chainResult = function (instance, obj) {
return instance._chain ? _(obj).chain() : obj;
};
_.mixin = function(obj) {
_.each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return chainResult(this, func.apply(_, args));
};
});
return _;
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
系列文章
The text was updated successfully, but these errors were encountered: