2020-10-06 23:10:08 +05:30

2.3 KiB

id, challengeType, videoUrl, forumTopicId, title
id challengeType videoUrl forumTopicId title
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();