Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

javascript - var关键字的目的是什么?何时应使用(或省略)?(What is the purpose of the var keyword and when should I use it (or omit it)?)

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.

(注意 :从ECMAScript版本3或5的角度提出了此问题。随着ECMAScript 6版本中引入新功能,答案可能会过时。)

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

(JavaScript中var关键字的功能到底是什么,它们之间有什么区别)

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?

(您什么时候会使用其中一个?为什么/会做什么?)

  ask by Alex translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're in the global scope then there's not much difference.

(如果您位于全球范围内,则没有太大区别。)

Read Kangax's answer for explanation

(阅读Kangax的答案以获取解释)

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

(如果您在函数中,则var将创建一个局部变量,“ no var”将查找作用域链,直到找到该变量或达到全局作用域为止(此时将创建它):)

// 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
    }())
}

If you're not doing an assignment then you need to use var :

(如果您不进行分配,则需要使用var :)

var x; // Declare x

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...