javascript - var 关键字的用途是什么以及何时应该使用它(或省略它)?

标签 javascript keyword ecmascript-5

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.

JavaScript中var关键字的作用到底是什么,有什么区别

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

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

您什么时候会使用其中任何一个,为什么/它有什么作用?

最佳答案

如果您处于全局范围内,则没有太大区别。阅读 Kangax's回答解释

如果你在一个函数中,那么 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
    }())
}

如果您不进行作业,则需要使用var:

var x; // Declare x

关于javascript - var 关键字的用途是什么以及何时应该使用它(或省略它)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45031266/

相关文章:

java - 如何在 Java Eclipse 中将不同的关键字设置为不同的颜色?

javascript - Typescript/Javascript - 使用 new String() 和 s = '' 声明变量

javascript - 需要帮助反向地理编码将消息附加到 GLatLng 坐标

nlp - 自然语言搜索(用户意图搜索)

php - 使用 PHP 从(搜索引擎)引用网址获取关键字

javascript - 从数组中的多个对象过滤属性

javascript - 如何使用 ES5 扩展 ES6 类?

javascript - ECMAScript 5.1 规范不正确?日期构造函数日期/时间格式解析为 UTC

javascript - Angular 中的 UI 网格刷新

javascript - ASP.Net MVC3 : Place . js 文件靠近 View 而不是脚本文件夹