Is using 'var' to declare variables option

2018-12-31 08:32发布

This question already has an answer here:

Is "var" optional?

myObj = 1;

same as ?

var myObj = 1;

I found they both work from my test, I assume var is optional. Is that right?

标签: javascript
14条回答
深知你不懂我心
2楼-- · 2018-12-31 09:18

This is one of the tricky parts of Javascript, but also one of its core features. A variable declared with var "begins its life" right where you declare it. If you leave out the var, it's like you're talking about a variable that you have used before.

var foo = 'first time use';
foo = 'second time use';

With regards to scope, it is not true that variables automatically become global. Rather, Javascript will traverse up the scope chain to see if you have used the variable before. If it finds an instance of a variable of the same name used before, it'll use that and whatever scope it was declared in. If it doesn't encounter the variable anywhere it'll eventually hit the global object (window in a browser) and will attach the variable to it.

var foo = "I'm global";
var bar = "So am I";

function () {
    var foo = "I'm local, the previous 'foo' didn't notice a thing";
    var baz = "I'm local, too";

    function () {
        var foo = "I'm even more local, all three 'foos' have different values";
        baz = "I just changed 'baz' one scope higher, but it's still not global";
        bar = "I just changed the global 'bar' variable";
        xyz = "I just created a new global variable";
    }
}

This behavior is really powerful when used with nested functions and callbacks. Learning about what functions are and how scope works is the most important thing in Javascript.

查看更多
与风俱净
3楼-- · 2018-12-31 09:18

Check out this 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
查看更多
若你有天会懂
4楼-- · 2018-12-31 09:24

Var doesn't let you, the programmer, declare a variable because Javascript doesn't have variables. Javascript has objects. Var declares a name to an undefined object, explicitly. Assignment assigns a name as a handle to an object that has been given a value.

Using var tells the Javacript interpreter two things:

  1. not to use delegation reverse traversal look up value for the name, instead use this one
  2. not to delete the name

Omission of var tells the Javacript interpreter to use the first-found previous instance of an object with the same name.

Var as a keyword arose from a poor decision by the language designer much in the same way that Javascript as a name arose from a poor decision.

ps. Study the code examples above.

查看更多
一个人的天荒地老
5楼-- · 2018-12-31 09:26

Everything about scope aside, they can be used differently.

console.out(var myObj=1);
//SyntaxError: Unexpected token var
console.out(myObj=1);
//1

Something something statement vs expression

查看更多
姐姐魅力值爆表
6楼-- · 2018-12-31 09:28

There's so much confusion around this subject, and none of the existing answers cover everything clearly and directly. Here are some examples with comments inline.

//this is a declaration
var foo;

//this is an assignment
bar = 3;

//this is a declaration and an assignment
var dual = 5;

A declaration sets a DontDelete flag. An assignment does not.

A declaration ties that variable to the current scope.

A variable assigned but not declared will look for a scope to attach itself to. That means it will traverse up the food-chain of scope until a variable with the same name is found. If none is found, it will be attached to the top-level scope (which is commonly referred to as global).

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
}

For a very clear description of what is happening, this analysis of the delete function covers variable instantiation and assignment extensively.

查看更多
心情的温度
7楼-- · 2018-12-31 09:28

The var keyword in Javascript is there for a purpose.

If you declare a variable without the var keyword, like this:

myVar = 100;

It becomes a global variable that can be accessed from any part of your script. If you did not do it intentionally or are not aware of it, it can cause you pain if you re-use the variable name at another place in your javascript.

If you declare the variable with the var keyword, like this:

var myVar = 100;

It is local to the scope ({] - braces, function, file, depending on where you placed it).

This a safer way to treat variables. So unless you are doing it on purpose try to declare variable with the var keyword and not without.

查看更多
登录 后发表回答