【发布时间】: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