扩展所有原型

瑞安·穆拉迪(Ryan Mulready)

我有一些jQuery原型方法:

$.fn.one
$.fn.two
$.fn.three

每个都有自己的代码,我想在所有三个代码的末尾添加一些内容。假设console.log('done')。这可能吗?

弗雷德里克·哈米迪(FrédéricHamidi)

您可以将名称重新绑定到调用其先前版本的新函数,然后调用console.log()

就像是:

$.each(["one", "two", "three"], function(index, name) {
    var originalMethod = $.fn[name];
    $.fn[name] = function() {
        var result = originalMethod.apply(this, arguments);
        console.log(name + "() done.");
        return result;
    };
});

如果您想将此行为应用于jQuery原型中的所有方法,则可以对其$.fn自身进行迭代,并且仅处理函数:

for (var name in $.fn) {
    // Create a new scope so 'originalMethod' is still bound to the
    // right method by the time our new '$.fn[name]()' is invoked.
    (function(originalMethod) {
        if ($.isFunction(originalMethod)) {
            $.fn[name] = function() {
                var result = originalMethod.apply(this, arguments);
                console.log(name + "() done.");
                return result;
            };
        }
    })($.fn[name]);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章