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:30

No, it is not "required", but it might as well be as it can cause major issues down the line if you don't. Not defining a variable with var put that variable inside the scope of the part of the code it's in. If you don't then it isn't contained in that scope and can overwrite previously defined variables with the same name that are outside the scope of the function you are in.

查看更多
余生无你
3楼-- · 2018-12-31 09:31

Nope, they are not equivalent.

With myObj = 1; you are using a global variable.

The latter declaration create a variable local to the scope you are using.

Try the following code to understand the differences:

external = 5;
function firsttry() {
  var external = 6;
  alert("first Try: " + external);
}

function secondtry() {
  external = 7;
  alert("second Try: " + external);
}

alert(external); // Prints 5
firsttry(); // Prints 6
alert(external); // Prints 5
secondtry(); // Prints 7
alert(external); // Prints 7

The second function alters the value of the global variable "external", but the first function doesn't.

查看更多
登录 后发表回答