【问题标题】:Trying to create a wrapper for jQuery methods尝试为 jQuery 方法创建一个包装器
【发布时间】:2016-10-21 09:09:29
【问题描述】:

我希望为 jQuery 中的每个方法创建一个包装器,例如每次调用该方法时都会输出一个 console.log。 不知道我错过了什么。

从包装单个方法(addClass)开始 像这样:

_addClass=jQuery.prototype.addClass;
jQuery.prototype.addClass = function () {
    var args = [].slice.call(arguments, 0);
    console.log('addClass arguments',args);
    return _addClass.apply(this, args);
};
$('body').addClass('blue')

这对我来说效果很好。 接下来我尝试遍历所有我遇到困难的 jQuery 方法:

function wrapClass (o)
{
    for (var m in o.prototype)
    {
        if (typeof(o.prototype[m]) === "function")
        {
             console.log('wrapping ',m);
             var _temp=o.prototype[m];
             o.prototype[m] = function () {
                var args = [].slice.call(arguments, 0);
                console.log(m+' arguments',args);
                return _temp.apply(this, args);
            };
        }
    }
};
wrapClass(jQuery);

这会产生一个 TypeError “this.off 不是函数”

还尝试(根据 Barni 的评论)创建一个像这样的闭包:

function wrapClass (o)
{
    for (var m in o.prototype)
    {
        if (typeof(o.prototype[m]) === "function")
        {
            (function(){
                var _temp=o.prototype[m];
                console.log('wrapping ',m,typeof(_temp));
                        o.prototype[m] = function () {
                        var args = [].slice.call(arguments, 0);
                        console.log(m+' arguments',args);
                        return _temp.apply(this, args);
                };
            })(m);
        }
    }
};
wrapClass(jQuery);
$('body').addClass('blue');

但现在我得到以下输出和错误:

undelegate arguments ["body", undefined]
undelegate arguments ["body"]
undelegate arguments [Array[0]]
undelegate arguments []
undelegate arguments [undefined, undefined]
Uncaught TypeError: $(...).addClass is not a function

谢谢

【问题讨论】:

  • 您可以尝试登录o.prototype[m]m 以查看addClass 是哪种类型。也许它不是一个函数类型,而是你需要考虑的其他东西?

标签: javascript methods prototype wrapper


【解决方案1】:

变量 _temp 有问题。您在函数 wrapClass 的范围内创建此变量,因此您在每次循环迭代中覆盖它。最后,你总是有最后一个 jQuery 方法(可能是取消委托)。
我没有分析整个案例,但是在你的循环之后你总是调用最后一个方法,不管你调用什么 jQuery 函数。

【讨论】:

  • 谢谢巴尼。我怀疑是这样的,所以我需要创建一个外壳?
猜你喜欢
  • 2012-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-17
  • 1970-01-01
  • 1970-01-01
  • 2015-04-07
  • 1970-01-01
相关资源
最近更新 更多