3.0 KiB
3.0 KiB
id, title, challengeType, videoUrl, localeTitle
id | title | challengeType | videoUrl | localeTitle |
---|---|---|---|---|
56533eb9ac21ba0edf2244be | Global Scope and Functions | 1 | 全球范围和职能 |
Description
var
关键字的情况下使用的变量将在global
范围内自动创建。这可能会在代码中的其他位置或再次运行函数时产生意外后果。您应该始终使用var
声明变量。 Instructions
var
,在任何函数之外声明一个global
变量myGlobal
。使用值10
初始化它。在函数fun1
内部,在不使用var
关键字的情况下为oopsGlobal
分配5
。 Tests
tests:
- text: 应该定义<code>myGlobal</code>
testString: 'assert(typeof myGlobal != "undefined", "<code>myGlobal</code> should be defined");'
- text: <code>myGlobal</code>的值应为<code>10</code>
testString: 'assert(myGlobal === 10, "<code>myGlobal</code> should have a value of <code>10</code>");'
- text: 应使用<code>var</code>关键字声明<code>myGlobal</code>
testString: 'assert(/var\s+myGlobal/.test(code), "<code>myGlobal</code> should be declared using the <code>var</code> keyword");'
- text: <code>oopsGlobal</code>应该是一个全局变量,其值为<code>5</code>
testString: 'assert(typeof oopsGlobal != "undefined" && oopsGlobal === 5, "<code>oopsGlobal</code> should be a global variable and have a value of <code>5</code>");'
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
console.info('after the test');
Solution
// solution required