在某些情况下,我喜欢通过在变量名称前加上前缀来按上下文对变量进行分组,例如(示例 1)
var context_var1 = "value";
var context_var2 = "value";
var context_var3 = "value";
var context_var4 = "value";
现在我要写一个脚本,我看看不同的声明风格,比如“only-one-var-keyword-style”(示例2)
var context_var1 = "value",
context_var2 = "value",
context_var3 = "value",
context_var4 = "value";
或“逗号优先样式”(示例 3)
var context_var1 = "value"
, context_var2 = "value"
, context_var3 = "value"
, context_var4 = "value"
;
. 但说实话,我真的最喜欢第一个例子。我个人认为它是最易读的风格。但是我想到了以下几点:
var context = {
var1 : "value",
var2 : "value",
var3 : "value
};
然后我可以通过
console.log(context.var1);
所以你怎么看。使用 JavaScript 对象作为某种变量存储是个好主意吗?
编辑:由于它被请求了几次,下面是一个真实的例子,我将一些变量存储到一个对象中。
/**
*
* Dom nodes which will be used a couple of times on various places.
* Grouped into an object by context.
*
* @type {DOM nodes}
*
*/
var $dom = {
document : $( document ),
head : $( "head" ),
body : $( "body" )
};
/**
*
* Calculate values based on the document height and
* window width.
*
* @return {Object}
*
*/
var gauge = function() {
var body_fontsize = parseInt($dom.body
.css( "font-size" )
.replace( "px", "" ), 10
);
var window_width = window.screen.availWidth;
var document_height = $dom.document.height();
var bline_count = Math.round( document_height / body_fontsize );
var vline_count = Math.round( window_width / body_fontsize );
return {
width : window_width,
height : document_height,
baselines : bline_count,
vertlines : vline_count
};
};