freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../basic-javascript/global-scope-and-functions.md

2.7 KiB

id title challengeType videoUrl forumTopicId dashedName
56533eb9ac21ba0edf2244be 全局作用域和函数 1 https://scrimba.com/c/cQM7mCN 18193 global-scope-and-functions

--description--

在 JavaScript 中,作用域涉及到变量的作用范围。 在函数外定义的变量具有 全局 作用域。 这意味着,具有全局作用域的变量可以在代码的任何地方被调用。

未使用 letconst 关键字声明的变量会在 global 范围内自动创建。 当在代码其他地方无意间定义了一个变量,刚好变量名与全局变量相同,这时会产生意想不到的后果。 你应该总是用 letconst 声明你的变量。

--instructions--

使用 letconst,在任何函数之外声明一个名为 myGlobal 的全局变量。 并给它一个初始值 10

在函数 fun1 中,不要 使用 letconst 关键字,将 5 分配给 oopsGlobal

--hints--

应定义 myGlobal

assert(typeof myGlobal != 'undefined');

myGlobal 的值应为 10

assert(myGlobal === 10);

myGlobal 应该使用 letconst 关键字声明

assert(/(let|const)\s+myGlobal/.test(code));

oopsGlobal 应为全局变量,值为 5

assert(typeof oopsGlobal != 'undefined' && oopsGlobal === 5);

--seed--

--before-user-code--

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-user-code--

fun1();
fun2();
uncapture();
(function() { return logOutput || "console.log never called"; })();

--seed-contents--

// Declare the myGlobal variable below this line


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);
}

--solutions--

const myGlobal = 10;

function fun1() {
  oopsGlobal = 5;
}

function fun2() {
  var output = "";
  if(typeof myGlobal != "undefined") {
    output += "myGlobal: " + myGlobal;
  }
  if(typeof oopsGlobal != "undefined") {
    output += " oopsGlobal: " + oopsGlobal;
  }
  console.log(output);
}