javascript - 简单的 jquery 包装器不能完全工作

标签 javascript jquery

我用我认为简单的包装器包装了 jquery,但是任何将函数作为参数的函数似乎都不起作用(该函数从未被调用)。

class $Util {
    // jquery wrapper
    // use with .apply(this...)
    static $() {
        if (!this.$wrapper)
            throw new ReferenceError('$Util.$: $wrapper not defined in context of this');
        var shift = [].shift;
        var fn = shift.apply(arguments);
        this.$wrapper[fn](arguments);
        return this;
    }
}

class Foo {
    constructor() {
        this.$wrapper = $('#foo');
        return this;
    }
    $() {
        $Util.$.apply(this, arguments);
        return this;
    }
}

var f = new Foo().$('appendTo', $('body')); // no problem
f.$('slideUp', function() {
    console.log(" i never log !");
});
f.$wrapper.slideUp(function() {
    console.log(" but i do !");
});

https://jsfiddle.net/0v0b6k5q/

最佳答案

由于某种原因,将参数更改为 ...arguments 就成功了。

 class $Util {
        // jquery wrapper
        // use with .apply(this...)
        static $() {
            if (!this.$wrapper)
                throw new ReferenceError('$Util.$: $wrapper not defined in context of this');
            var shift = [].shift;
            var fn = shift.apply(arguments);
            this.$wrapper[fn](...arguments);
            return this;
        }
    }

关于javascript - 简单的 jquery 包装器不能完全工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38289022/

相关文章:

javascript - 如何通过单击 Jquery 中的标题对表格列进行排序?

javascript - 创建一个有全局二级索引错误的表

javascript - backbone.js 集合和多种类型的模型?

javascript - 将另一个(父) Controller 逻辑注入(inject)派生状态(angularjs ui-router)

javascript - 找不到模块子进程

javascript - 带有附加外部页面的 jQuery ajax 加载页面

javascript - 等待多个调用的最佳实践

javascript - 如何使用 jQuery 在动态 DOM 元素上使用 .insertAfter?

javascript - 如何在绑定(bind)事件期间排除元素

javascript - 根据其他 div 高度设置动画 div 高度