2.3 KiB
2.3 KiB
id, challengeType, videoUrl, forumTopicId, localeTitle
id | challengeType | videoUrl | forumTopicId | localeTitle |
---|---|---|---|---|
56533eb9ac21ba0edf2244bf | 1 | https://scrimba.com/c/cd62NhM | 18227 | 局部作用域和函数 |
Description
myTest
内声明局部变量loc
的例子:
function myTest() {
var loc = "foo";
console.log(loc);
}
myTest(); // logs "foo"
console.log(loc); // loc is not defined
在函数外,loc
是未定义的。
Instructions
myFunction
内部声明一个局部变量myVar
,并删除外部的 console.log。
提示:如果你遇到了问题,可以先尝试刷新页面。
Tests
tests:
- text: 未找到全局的<code>myVar</code>变量。
testString: assert(typeof myVar === 'undefined');
- text: 需要定义局部的<code>myVar</code>变量。
testString: assert(/var\s+myVar/.test(code));
Challenge Seed
function myLocalScope() {
'use strict'; // you shouldn't need to edit this line
console.log(myVar);
}
myLocalScope();
// Run and check the console
// myVar is not defined outside of myLocalScope
console.log(myVar);
// Now remove the console log line to pass the test
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;
}
After Test
typeof myLocalScope === 'function' && (capture(), myLocalScope(), uncapture());
(function() { return logOutput || "console.log never called"; })();
Solution
function myLocalScope() {
'use strict';
var myVar;
console.log(myVar);
}
myLocalScope();