You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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为什么你要这么做)。
The text was updated successfully, but these errors were encountered:
原文地址
2017年12月14日
Defining and updating JavaScript variables in different scopes
昨天,我们学习了关于JavaScript作用域。今天,我们来学习如何去在不同类型的作用域中更新变量。
用前缀var来定义一个新的变量。省略var会更新一个存在的变量的值。
关于这方面有两条建议:
你可以在函数里面定义一个和全局作用域或者词法作用域中同名的变量,也不会对那个变量造成影响。
如果你省略了开头的var,你可以在内部函数内部修改全局作用域或者词法作用域中的那个变量。
明天,我们会学不在全局作用域中保存变量(and为什么你要这么做)。
The text was updated successfully, but these errors were encountered: