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

3.2 KiB
Raw Blame History

id, challengeType, videoUrl, forumTopicId, localeTitle
id challengeType videoUrl forumTopicId localeTitle
56533eb9ac21ba0edf2244be 1 https://scrimba.com/c/cQM7mCN 18193 全局作用域和函数

Description

在 JavaScript 中,作用域涉及到变量的作用范围。在函数外定义的变量具有 全局 作用域。这意味着,具有全局作用域的变量可以在代码的任何地方被调用。 这些没有使用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);
}