我发现了一种扩展核心 jQuery init 函数的方法(每当您使用 $() 或 jQuery() 函数时都会调用该函数)。使用普通代理模式这是不可能的,但以下代码使其工作:
var origInit = jQuery.fn.init;
jQuery.fn.init = function(selector, context, rootjQuery) {
if (some condition) {
//custom code here, possibly returning some other jQuery object than
//what jQuery would normally return
}
return origInit.call(jQuery.fn, selector, context, rootjQuery);
}
我的问题是这可能有用的地方,因为我意识到我最初使用它来缓存选择器的意图是有问题的(因为它会影响其他插件的行为——我最终使用了一个单独的函数进行缓存)。
所以我想我会分享这个方法,我也很想听听其他关于它潜在用途的想法。我想也许它可以用来支持某种自定义选择器,虽然我不确定什么时候需要,因为 jQuery 已经提供了很多选择器。