I have found that it does not seem necessary to use the keyword 'var' when declaring a variable in Javascript. In fact, I have found no bad side effects from omitting it altogether.

Perhaps this is bad form, but can someone explain why it would be necessary?

有帮助吗?

解决方案

Using the keyword var ensures that your variable is properly scoped. If you do not use the keyword, then JavaScript will automatically create the variable as a global scope, which can cause issues later in the execution of your page.

name = 'Bic'; // implicitly global

function myFunc() {
    var name = 'John'; // this variable is scoped here
    console.log(name); // John
    getName(); // Bic
}

function getName() {
    console.log(name); //Bic
}

myFunc();
getName();

In the code above, I declared a global name, and a scoped name. Note, the global name lingers on after myFunc() has finished executing. name is a property of most HTML elements. In this particular answer, my declaration of name without the var keyword can have detrimental affects to a page's execution. The value of name gets thrown out of scope, and this can affect targeting elements, and other things. If you take a look at this Fiddle, and click Run again after it loads, you will notice it automatically opens a new tab. This is because the original value of name has been clobbered, and the page does not know where to truly open.

As a general rule, it is good to always declare variables with the var keyword, as this makes it easier to follow the scope of that variable, as avoids unforeseen issues they can cause.

As was noted by Pointy, the 'use strict' pragma (introduced in ECMAScript 5) actually prohibits the declaration of variables without the var keyword.

其他提示

if you don't declare it, perhaps you are accessing a global var. be careful with that because you can get undesired side effects.

By definition, declaring a variable requires the var keyword. There are other ways of creating variables though, such as including them in a formal parameter list:

function foo(a, b, c) {...}

here a, b, and c are created more or less as if they were declared with var. The ill effects of creating variables without var are noted in other answers.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top