3.2 KiB
3.2 KiB
id, title, challengeType, videoUrl, forumTopicId, localeTitle
id | title | challengeType | videoUrl | forumTopicId | localeTitle |
---|---|---|---|---|---|
56533eb9ac21ba0edf2244be | Global Scope and Functions | 1 | https://scrimba.com/c/cQM7mCN | 18193 | 全局作用域和函数 |
Description
var
关键字定义的变量,会被自动创建在全局作用域中,形成全局变量。当在代码其他地方无意间定义了一个变量,刚好变量名与全局变量相同,这时会产生意想不到的后果。因此你应该总是使用var关键字来声明你的变量。
Instructions
全局
变量myGlobal
,并给它一个初始值10
在函数fun1
的内部,不使用var
关键字来声明oopsGlobal
,并赋值为5
。
Tests
tests:
- text: 应定义<code>myGlobal</code>。
testString: assert(typeof myGlobal != "undefined");
- text: <code>myGlobal</code>的值应为<code>10</code>。
testString: assert(myGlobal === 10);
- text: 应使用<code>var</code>关键字定义<code>myGlobal</code>。
testString: assert(/var\s+myGlobal/.test(code));
- text: <code>oopsGlobal</code>应为全局变量且值为<code>5</code>。
testString: assert(typeof oopsGlobal != "undefined" && oopsGlobal === 5);
Challenge Seed
// 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
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
fun1();
fun2();
uncapture();
(function() { return logOutput || "console.log never called"; })();
Solution
// Declare your variable here
var myGlobal = 10;
function fun1() {
// Assign 5 to oopsGlobal Here
oopsGlobal = 5;
}
// 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);
}