ran*_*mor 4 javascript coding-style
所以我听说在没有"var"的情况下初始化的js中的变量将是全局变量.所以:
$(document).ready(function(){
function foo(){
//since i'm not using "var", will this function become global?
}
var bar = function(){
//is this the better way to declare the function?
}
})
Run Code Online (Sandbox Code Playgroud)
如果它是全局的,为什么我无法在控制台中访问它.如果它不是全局的,并且它的范围在函数中,那么省略"var"会花费一些性能吗?谢谢.
Eri*_*lin 13
只有声明的变量不会var变为全局变量,这不适用于函数.
但是,您可以这样声明foo:
foo = function() {}
Run Code Online (Sandbox Code Playgroud)
它应该是全球性的.
var由于这些原因,通常不建议省略(不在头顶):
for(i = 0; i < arr.length; i++)(注意缺乏var)var由于名为hoisting的语言功能,您可能希望使用声明函数
顺便说一句,如果您选择使用声明函数var,我建议您这样做:
var foo = function foo() {}
Run Code Online (Sandbox Code Playgroud)
因为它给函数一个"名称"而不是被视为匿名函数,这将有助于调试.function我相信,大多数人不这样做并宣布使用.
| 归档时间: |
|
| 查看次数: |
5377 次 |
| 最近记录: |