2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
id: 56533eb9ac21ba0edf2244bf
|
2020-12-16 00:37:30 -07:00
|
|
|
title: 局部作用域和函数
|
2018-10-10 18:03:03 -04:00
|
|
|
challengeType: 1
|
2020-04-29 18:29:13 +08:00
|
|
|
videoUrl: 'https://scrimba.com/c/cd62NhM'
|
|
|
|
forumTopicId: 18227
|
2021-01-13 03:31:00 +01:00
|
|
|
dashedName: local-scope-and-functions
|
2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --description--
|
|
|
|
|
2020-04-29 18:29:13 +08:00
|
|
|
在一个函数内声明的变量,以及该函数的参数都是局部变量,意味着它们只在该函数内可见。
|
2020-12-16 00:37:30 -07:00
|
|
|
|
|
|
|
这是在函数`myTest`内声明局部变量`loc`的例子:
|
2020-04-29 18:29:13 +08:00
|
|
|
|
|
|
|
```js
|
|
|
|
function myTest() {
|
|
|
|
var loc = "foo";
|
|
|
|
console.log(loc);
|
|
|
|
}
|
|
|
|
myTest(); // logs "foo"
|
|
|
|
console.log(loc); // loc is not defined
|
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
在函数外,`loc`是未定义的。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --instructions--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
在函数`myFunction`内部声明一个局部变量`myVar`,并删除外部的 console.log。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
**提示:**
|
|
|
|
如果你遇到了问题,可以先尝试刷新页面。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --hints--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
未找到全局的`myVar`变量。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
assert(typeof myVar === 'undefined');
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
需要定义局部的`myVar`变量。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
assert(/var\s+myVar/.test(code));
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
# --seed--
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
```js
|
|
|
|
function myLocalScope() {
|
|
|
|
|
|
|
|
// Only change code below this line
|
|
|
|
|
|
|
|
console.log('inside myLocalScope', myVar);
|
|
|
|
}
|
|
|
|
myLocalScope();
|
|
|
|
|
|
|
|
// Run and check the console
|
|
|
|
// myVar is not defined outside of myLocalScope
|
|
|
|
console.log('outside myLocalScope', myVar);
|
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --solutions--
|
2020-04-29 18:29:13 +08:00
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
```js
|
|
|
|
function myLocalScope() {
|
|
|
|
|
|
|
|
// Only change code below this line
|
|
|
|
var myVar;
|
|
|
|
console.log('inside myLocalScope', myVar);
|
|
|
|
}
|
|
|
|
myLocalScope();
|
|
|
|
|
|
|
|
// Run and check the console
|
|
|
|
// myVar is not defined outside of myLocalScope
|
|
|
|
console.log('outside myLocalScope', myVar);
|
|
|
|
```
|