Recetly 我一直在寻找我的 javascript 代码中的内存泄漏。在发现一些重大泄漏之后,我开始寻找较小的泄漏,并发现了一些可能是潜在泄漏的东西——“hoverIntent.js”插件。请问这真的是泄密还是我太热心了?
代码的一般模式(完整代码在这里http://cherne.net/brian/resources/jquery.hoverIntent.js):
(function($) {
$.fn.hoverIntent = function(f,g) {
//...
var track = function(ev) {
cX = ev.pageX;
cY = ev.pageY;
};
var compare = function(ev,ob) {
//... function body
};
var delay = function(ev,ob) {
//... function body
};
var handleHover = function(e) {
//... function body
};
return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover);
};
})(jQuery);
我知道很多 js 插件都是这样写的,但是......如果我每次hoverIntent
在我的对象上调用时都能正确地做到这一点,那么会创建 3 个新函数(闭包)吗?这不是可能的内存泄漏(或至少是性能问题)吗?
这样写不是更好吗:
(function($) {
//create the methods only once on module init?
var track = function(ev) {
cX = ev.pageX;
cY = ev.pageY;
};
var compare = function(ev,ob) {
//... function body
};
var delay = function(ev,ob) {
//... function body
};
var handleHover = function(e) {
//... function body
};
$.fn.hoverIntent = function(f,g) {
//no closures here
return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover);
};
})(jQuery);