--- id: 56533eb9ac21ba0edf2244be title: Global Scope and Functions challengeType: 1 videoUrl: '' localeTitle: 全球范围和职能 --- ## Description
在JavaScript中, 范围是指变量的可见性。在功能块之外定义的变量具有全局范围。这意味着,它们可以在JavaScript代码中随处可见。在没有var关键字的情况下使用的变量将在global范围内自动创建。这可能会在代码中的其他位置或再次运行函数时产生意外后果。您应该始终使用var声明变量。
## Instructions
使用var ,在任何函数之外声明一个global变量myGlobal 。使用值10初始化它。在函数fun1内部,在使用var关键字的情况下oopsGlobal分配5
## Tests
```yml tests: - text: 应该定义myGlobal testString: assert(typeof myGlobal != "undefined"); - text: myGlobal的值应为10 testString: assert(myGlobal === 10); - text: 应使用var关键字声明myGlobal testString: assert(/var\s+myGlobal/.test(code)); - text: oopsGlobal应该是一个全局变量,其值为5 testString: assert(typeof oopsGlobal != "undefined" && oopsGlobal === 5); ```
## Challenge Seed
```js // Declare your variable here function fun1() { // Assign 5 to oopsGlobal Here } // Only change code above this line function fun2() { var output = ""; if (typeof myGlobal != "undefined") { output += "myGlobal: " + myGlobal; } if (typeof oopsGlobal != "undefined") { output += " oopsGlobal: " + oopsGlobal; } console.log(output); } ```
### Before Test
```js var logOutput = ""; var originalConsole = console function capture() { var nativeLog = console.log; console.log = function (message) { logOutput = message; if(nativeLog.apply) { nativeLog.apply(originalConsole, arguments); } else { var nativeMsg = Array.prototype.slice.apply(arguments).join(' '); nativeLog(nativeMsg); } }; } function uncapture() { console.log = originalConsole.log; } var oopsGlobal; capture(); ```
### After Test
```js console.info('after the test'); ```
## Solution
```js // solution required ```