var是可选的吗?
myObj = 1;
和?
var myObj = 1;
我发现他们都工作从我的测试,我假设var是可选的。对吗?
var是可选的吗?
myObj = 1;
和?
var myObj = 1;
我发现他们都工作从我的测试,我假设var是可选的。对吗?
当前回答
看看这个Fiddle: http://jsfiddle.net/GWr6Z/2/
function doMe(){
a = "123"; // will be global
var b = "321"; // local to doMe
alert("a:"+a+" -- b:"+b);
b = "something else"; // still local (not global)
alert("a:"+a+" -- b:"+b);
};
doMe()
alert("a:"+a+" -- b:"+b); // `b` will not be defined, check console.log
其他回答
围绕着这个问题有太多的困惑,现有的答案没有一个能清晰直接地涵盖一切。下面是一些内联注释的例子。
//this is a declaration
var foo;
//this is an assignment
bar = 3;
//this is a declaration and an assignment
var dual = 5;
声明设置了一个DontDelete标志。作业则不然。
声明将该变量绑定到当前作用域。
赋值但未声明的变量将寻找要附加到的作用域。这意味着它将遍历范围的食物链,直到找到具有相同名称的变量。如果没有找到,它将被附加到顶层作用域(通常称为全局作用域)。
function example(){
//is a member of the scope defined by the function example
var foo;
//this function is also part of the scope of the function example
var bar = function(){
foo = 12; // traverses scope and assigns example.foo to 12
}
}
function something_different(){
foo = 15; // traverses scope and assigns global.foo to 15
}
为了非常清楚地描述发生了什么,本文对delete函数的分析广泛地涵盖了变量实例化和赋值。
They mean different things. If you use var the variable is declared within the scope you are in (e.g. of the function). If you don't use var, the variable bubbles up through the layers of scope until it encounters a variable by the given name or the global object (window, if you are doing it in the browser), where it then attaches. It is then very similar to a global variable. However, it can still be deleted with delete (most likely by someone else's code who also failed to use var). If you use var in the global scope, the variable is truly global and cannot be deleted.
在我看来,这是javascript中最危险的问题之一,应该弃用,或者至少在警告中提出警告。原因是,很容易忘记var,并偶然地将一个通用变量名绑定到全局对象。这会产生奇怪且难以调试的行为。
I just found the answer from a forum referred by one of my colleague. If you declare a variable outside a function, it's always global. No matter if you use var keyword or not. But, if you declare the variable inside a function, it has a big difference. Inside a function, if you declare the variable using var keyword, it will be local, but if you declare the variable without var keyword, it will be global. It can overwrite your previously declared variables. - See more at: http://forum.webdeveloperszone.com/question/what-is-the-difference-between-using-var-keyword-or-not-using-var-during-variable-declaration/#sthash.xNnLrwc3.dpuf
看看这个Fiddle: http://jsfiddle.net/GWr6Z/2/
function doMe(){
a = "123"; // will be global
var b = "321"; // local to doMe
alert("a:"+a+" -- b:"+b);
b = "something else"; // still local (not global)
alert("a:"+a+" -- b:"+b);
};
doMe()
alert("a:"+a+" -- b:"+b); // `b` will not be defined, check console.log
撇开范围不谈,它们可以用不同的方式使用。
console.out(var myObj=1);
//SyntaxError: Unexpected token var
console.out(myObj=1);
//1
语句和表达式