What is the purpose of the var keyword and when sh

2018-12-30 22:51发布

NOTE: This question was asked from the viewpoint of ECMAScript version 3 or 5. The answers might become outdated with the introduction of new features in the release of ECMAScript 6.

What exactly is the function of the var keyword in JavaScript, and what is the difference between

var someNumber = 2;
var someFunction = function() { doSomething; }
var someObject = { }
var someObject.someProperty = 5;

and

someNumber = 2;
someFunction = function() { doSomething; }
someObject = { }
someObject.someProperty = 5;

?

When would you use either one, and why/what does it do?

18条回答
荒废的爱情
2楼-- · 2018-12-30 22:56

I would say it's better to use var in most situations.

Local variables are always faster than the variables in global scope.

If you do not use var to declare a variable, the variable will be in global scope.

For more information, you can search "scope chain JavaScript" in Google.

查看更多
姐姐魅力值爆表
3楼-- · 2018-12-30 22:56

@Chris S gave a nice example showcasing the practical difference (and danger) between var and no var. Here's another one, I find this one particularly dangerous because the difference is only visible in an asynchronous environment so it can easily slip by during testing.

As you'd expect the following snippet outputs ["text"]:

function var_fun() {
  let array = []
  array.push('text')
  return array
}

console.log(var_fun())

So does the following snippet (note the missing let before array):

function var_fun() {
  array = []
  array.push('text')
  return array
}

console.log(var_fun())

Executing the data manipulation asynchronously still produces the same result with a single executor:

function var_fun() {
  array = [];
  return new Promise(resolve => resolve()).then(() => {
    array.push('text')
    return array
  })
}

var_fun().then(result => {console.log(result)})

But behaves differently with multiple ones:

function var_fun() {
  array = [];
  return new Promise(resolve => resolve()).then(() => {
    array.push('text')
    return array
  })
}

[1,2,3].forEach(i => {
  var_fun().then(result => {console.log(result)})
})

Using let however:

function var_fun() {
  let array = [];
  return new Promise(resolve => resolve()).then(() => {
    array.push('text')
    return array
  })
}

[1,2,3].forEach(i => {
  var_fun().then(result => {console.log(result)})
})

查看更多
后来的你喜欢了谁
4楼-- · 2018-12-30 22:57

Without using "var" variables can only define when set a value. In example:

my_var;

cannot work in global scope or any other scope. It should be with value like:

my_var = "value";

On the other hand you can define a vaiable like;

var my_var;

Its value is undefined ( Its value is not null and it is not equal to null interestingly.).

查看更多
素衣白纱
5楼-- · 2018-12-30 22:58

Without var - global variable.

Strongly recommended to ALWAYS use var statement, because init global variable in local context - is evil. But, if you need this dirty trick, you should write comment at start of page:

/* global: varname1, varname2... */
查看更多
看淡一切
6楼-- · 2018-12-30 23:00

When Javascript is executed in a browser, all your code is surrounded by a with statement, like so:

with (window) {
    //Your code
}

More info on with - MDN

Since var declares a variable in the current scope , there is no difference between declaring var inside window and not declaring it at all.

The difference comes when you're not directly inside the window, e.g. inside a function or inside a block.

Using var lets you hide external variables that have the same name. In this way you can simulate a "private" variable, but that's another topic.

A rule of thumb is to always use var, because otherwise you run the risk of introducing subtle bugs.

EDIT: After the critiques I received, I would like to emphasize the following:

  • var declares a variable in the current scope
  • The global scope is window
  • Not using var implicitly declares var in the global scope (window)
  • Declaring a variable in the global scope (window) using var is the same as omitting it.
  • Declaring a variable in scopes different from window using var is not the same thing as declaring a variable without var
  • Always declare var explicitly because it's good practice
查看更多
刘海飞了
7楼-- · 2018-12-30 23:01

You should use var keyword unless you intend to have the variable attached to window object in browser. Here's a link that explains scoping and difference between glocal scoping and local scoping with and wihtout var keyword.

When variables get defined without the use of var keyword, what it looks like is a simple “assignment” operation.

When the value is assigned to a variable in javascript, the interpreter first tries to find the “variable declaration” in the same context/scope as that of assignment. When the interpreter executes dummyVariable = 20, it looks up for the declaration of dummyVariable at beginning of the function. (Since all Variable declarations are moved to the beginning of the context by javascript interpreter and this is called hoisting)

You may also want to look at hoisting in javascript

查看更多
登录 后发表回答