Skip to content
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

Open
chenshuhong opened this issue Aug 27, 2019 · 4 comments
Open

如何手写一个自己的工具库 #16

chenshuhong opened this issue Aug 27, 2019 · 4 comments

Comments

@chenshuhong
Copy link
Owner

chenshuhong commented Aug 27, 2019

系列文章

@chenshuhong
Copy link
Owner Author

chenshuhong commented Aug 27, 2019

环境检测,window(web worker)=>global=>node vm=>小程序

var root = (typeof self == 'object' && self.self == self && self) ||
           (typeof global == 'object' && global.global == global && global) ||
           this ||
           {};

@chenshuhong
Copy link
Owner Author

chenshuhong commented Aug 27, 2019

支持函数式和面向对象调用方式

// 函数式风格
_.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(_);

@chenshuhong
Copy link
Owner Author

支持模块化导出

if (typeof exports != 'undefined' && !exports.nodeType) {
    if (typeof module != 'undefined' && !module.nodeType && module.exports) {
        exports = module.exports = _;
    }
    exports._ = _;
} else {
    root._ = _;
}

@chenshuhong
Copy link
Owner Author

chenshuhong commented Aug 27, 2019

链式调用
jQuery 之所以能实现链式调用,关键就在于通过 return this,返回调用对象
在 underscore 中,默认不使用链式调用,但是如果你想使用链式调用,你可以通过 _.chain 函数实现:

_.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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant