需要帮助了解返回功能和范围

时间:2018-01-30 11:47:16

标签: javascript

所以我基本上只是想学习javascript ...所以我基本上只是制作函数并测试它们以查看结果。我认为这个代码位应该可行,但它只是返回NaN ...有人可以告诉我我做错了什么吗?

<!DOCTYPE html>
<html>
<body>
<p id = "test"> Hello World</p>
  <script>function testFunction(data)
    {
      var x = data;
      var y = 3;
      var z = x + y;
      function testShow(z)
      {
         var b = z * x;
         return  b;
      }  
     return testShow();
  }
   document.getElementById("test").innerHTML = testFunction(2);
</script>
<button type ="button" onclick ="testFunction()">Click me</button>
</body>
</html>

我还试图在返回document.getElementById之后放置testShow() ... RIGHT;当我这样做时,我得到了Hello World,但按钮没有返回任何内容或更改Hello World消息......

2 个答案:

答案 0 :(得分:3)

当您致电testShow时,您不会传递任何论据。

这意味着z(这是testShow的第一个参数 - 并且掩盖z的更广范围内的另一个x + y是{{ 1}}。

因此,{p> undefinedz * xundefined * 2是显示的内容。

答案 1 :(得分:0)

<!DOCTYPE html>
<html>
<body>
    <p id = "test"> Hello World</p>
    <button type ="button" onclick ="document.getElementById('test').innerHTML = testFunction(2)">Click me</button>
    <script>
        function testFunction(data){ // just a structure
            var x = data; //2
            var y = 3; // 3
            var z = x + y; //5
            function testShow(aNumber){ // just a structure
                var b = aNumber * x; // 5*2 = 10
                return  b;
            }  
            return testShow(z); // function is executed where aNumber = z
        }
    </script>
</body>
</html> 

您希望避免在嵌套函数中使用相同的变量名,即使它在函数中被覆盖,也会导致混淆。

如果你把z写为testShow的参数,那么它不是var z = x + y因此最好更改名称

您可以将按钮放在脚本上方,因为在您单击按钮时脚本存在。

或者,您可以使用ES6语法编写函数,并使用this代替var,因为一旦您理解它就会更容易阅读。

function testFunction(data){
    this.x = data; 
    this.y = 3; 
    this.z = x + y;
    this.testShow = aNumber => aNumber * this.x;
    return this.testShow(this.z);
}

ES5(您正在编写的版本)中的this.testShow是什么样的

this.testShow = function(aNumber){
    return aNumber * this.x;
}.bind(this);

所以你可以看到我们需要写多少额外的两个数字

我创建按钮侦听器的首选方法。

<button id="testButton" type="button">Click me</button>

document.getElementById('testButton').addEventListener('click', function(event){
    document.getElementById('test').innerHTML = testFunction(data);
});

现在HTML看起来更漂亮了

相关问题