Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Daily Tips翻译]Defining and updating JavaScript variables in different scopes #10

Open
Pomelo1213 opened this issue Feb 6, 2018 · 0 comments
Labels
学到了知识 learning 翻译 translate

Comments

@Pomelo1213
Copy link
Owner

原文地址

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为什么你要这么做)。

@Pomelo1213 Pomelo1213 added 学到了知识 learning 翻译 translate labels Aug 21, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
学到了知识 learning 翻译 translate
Projects
None yet
Development

No branches or pull requests

1 participant