[英]who can help me optimized this javascript code?
这是我的部分代码,但朋友说变量(如getStyle,getOffsetWidth,getOffsetHeight,log)不会发布,所以我想知道为什么变量不会发布,以及如何优化它,谢谢!
var Util = (function() {
"use strict";
var getStyle = function(node) {
var style = null;
if (window.getComputedStyle) {
style = window.getComputedStyle(node, null);
} else {
style = node.currentStyle;
}
return style;
};
var getOffsetWidth = function(style) {
return parseInt(style.width, 10) +
parseInt(style.paddingLeft, 10) +
parseInt(style.paddingRight, 10) +
parseInt(style.marginLeft, 10) +
parseInt(style.marginRight, 10);
};
var getOffsetHeight = function(style) {
return parseInt(style.height, 10) +
parseInt(style.paddingTop, 10) +
parseInt(style.paddingBottom, 10) +
parseInt(style.marginTop, 10) +
parseInt(style.marginBottom, 10);
};
var log = function() {
if (window.console && window.console.log) {
window.console.log(arguments);
}
};
return {
getStyle: getStyle,
getOffsetWidth: getOffsetWidth,
getOffsetHeight: getOffsetHeight,
log: log
};
}());
你的朋友可能指的是变量getStyle
, getOffsetWidth
等包含在返回方法的闭包中。 这有点效率低,因为这些变量从未再次使用过。
在这种简单的情况下, Util
对象中的函数没有使用外部函数的闭包,没有理由不这样做:
var Util = {
getStyle: function(style) {
return parseInt(style.width) + ...
},
getOffsetWidth: ...
};
是的,这是一个用模块模式编写的模块。
自我执行的匿名函数形成一个闭包 - 或者如果你是如此思想(我不是)那么一组闭包 - 建立通过返回表达式公开的四个特权方法作为Util
属性。
此模式还可能包含私有变量/方法,这些变量/方法与getStyle
, getOffsetWidth
等完全相同,但不通过返回表达式公开。
这是建立一个或多个单例“命名空间”对象的完全有效的方法,这正是模块模式的目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.