3.0 KiB
Raw Blame History

id, title, challengeType, videoUrl, localeTitle
id title challengeType videoUrl localeTitle
56533eb9ac21ba0edf2244be Global Scope and Functions 1 全球范围和职能

Description

在JavaScript中 范围是指变量的可见性。在功能块之外定义的变量具有全局范围。这意味着它们可以在JavaScript代码中随处可见。在没有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