简单的jquery包装器不能完全正常工作

时间:2016-07-10 05:48:25

标签: 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/

1 个答案:

答案 0 :(得分:1)

由于某些原因,将参数更改为......参数就可以了。

 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;
        }
    }