var 关键字的用途是什么,我应该什么时候使用(或省略它)? [英] What is the purpose of the var keyword and when should I use it (or omit it)?

查看:27
本文介绍了var 关键字的用途是什么,我应该什么时候使用(或省略它)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这个问题是从 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.

JavaScript中var关键字的作用到底是什么,和

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆