var关键字的目的是什么?我何时应该使用它(或省略它)? [英] What is the purpose of the var keyword and when should I use it (or omit it)?
问题描述
注意:这个问题是从ECMAScript版本3或5的角度提出的。答案可能会因发布新功能而过时ECMAScript 6。
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.
var $ c $的功能究竟是什么c> JavaScript中的关键字,有什么区别
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;
和
someNumber = 2;
someFunction = function() { doSomething; }
someObject = { }
someObject.someProperty = 5;
?
你什么时候使用一个,为什么/它做什么?
When would you use either one, and why/what does it do?
推荐答案
如果你处于全球范围内,那么差别不大。阅读 Kangax的答案以获得解释
If you're in the global scope then there's not much difference. Read Kangax's answer for explanation
如果您在函数然后 var
将创建一个局部变量,no var将查找范围链,直到找到变量或命中全局范围(此时它将创建它):
If you're in a function then var
will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it):
// These are both globals
var foo = 1;
bar = 2;
function()
{
var foo = 1; // Local
bar = 2; // Global
// Execute an anonymous function
(function()
{
var wibble = 1; // Local
foo = 2; // Inherits from scope above (creating a closure)
moo = 3; // Global
}())
}
如果你没有完成任务,那么你需要使用 var
:
If you're not doing an assignment then you need to use var
:
var x; // Declare x
这篇关于var关键字的目的是什么?我何时应该使用它(或省略它)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!