[翻译]Defining and updating JavaScript variables in different scopes

294 阅读1分钟

原文地址(翻译练手)

2017年12月14日

Defining and updating JavaScript variables in different scopes

昨天,我们学习了关于JavaScript作用域。今天,我们来学习如何去在不同类型的作用域中更新变量。

用前缀var来定义一个新的变量。省略var会更新一个存在的变量的值。

关于这方面有两条建议:

  1. 如果一个变量已经被定义在当前作用域,用var再次声明它会抛出错误。
  2. 如果一个变量没有在当前作用域定义,省略var会创造新的变量(就算如此,建议你还是使用var定义。)

你可以在函数里面定义一个和全局作用域或者词法作用域中同名的变量,也不会对那个变量造成影响。

var sandwich = 'tuna';

var logSandwich = function () {
	// logs "turkey"
	// Does NOT update the global `sandwich` variable
	var sandwich = 'turkey';
	console.log(sandwich);

};
logSandwich();

// logs "tuna"
console.log(sandwich);

如果你省略了开头的var,你可以在内部函数内部修改全局作用域或者词法作用域中的那个变量。

var sandwich = 'tuna';

// logs "tuna"
console.log(sandwich);

var logSandwich = function () {
	// logs "tuna"
	console.log(sandwich);

	// Updates `sandwich` in the global scope
	sandwich = 'turkey';

	// logs "turkey"
	console.log(sandwich);

};
logSandwich();

// logs "turkey"
console.log(sandwich);

明天,我们会学不在全局作用域中保存变量(and为什么你要这么做)。