gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:28:17 25 4
gpt4 key购买 nike

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/22162592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com