【发布时间】:2013-06-04 08:18:10
【问题描述】:
在为变量赋值之前在 javascript 中声明变量是否有类似的最佳实践?有时出于范围原因需要,但如果范围无关紧要怎么办?
// Declare first
(function() {
var foo = 'bar',
a = 500,
b = 300,
c;
// Some things get done here with a and b before c can use them...
c = a * b;
// c is now ready to use...
doSomething(c);
}());
// Declare when needed
(function() {
var foo = 'bar',
a = 500,
b = 300;
// Some things get done here with a and b before c can use them...
var c = a * b;
// c is now ready to use...
doSomething(c);
}());
我也想知道对于类似对象文字的最佳实践是什么:
// Add property with null assigned to it
var myObj = {
foo: null,
doSomething: function() {
this.foo = 'bar';
}
};
// Property gets added when value is set
var myObj = {
doSomething: function() {
this.foo = 'bar';
}
};
【问题讨论】:
-
主要是风格问题。 Crockford 建议在作用域的顶部声明所有变量,这有时有助于消除一些常见的误解(例如,
for循环内的var声明实际上属于for之外的作用域)。 -
@FabrícioMatté 谢谢!甚至没有想过
for循环,但它确实有道理。
标签: javascript