【问题标题】:Why does this function have different answers, doesn't the function execute in where it was defined? [duplicate]为什么这个函数有不同的答案,函数没有在它定义的地方执行? [复制]
【发布时间】:2016-11-07 07:53:53
【问题描述】:

为什么ss()有不同的答案,函数不是在它定义的地方执行吗?

var scope="global";  

function t(){  
    console.log(scope);  

    function ss()
    {
        console.log(scope);  
    } 

    var scope="local";
    ss();
}

t(); 
ss();

它记录:

undefined
local
undefined

【问题讨论】:

  • 这样做:var scope="global"; function t() { console.log(scope); function ss() { console.log(scope); } scope="local"; ss(); return null; } t(); 因为作用域被定义为一个全局变量,你不能在一个函数中重复初始化同一个变量。你只能改变它的值!

标签: javascript scope


【解决方案1】:

首先你有一个重复的命名变量,第二个“本地”在函数下面,所以它会读取上面的,如果你想传递它们,你想要一个像这样的函数参数:

var scope="global";  
function t(e) {  
  console.log(e);
}  
function ss(e) {
  console.log(e);  
} 

scope="local";
t(scope); 
ss(scope);

【讨论】:

  • 你完全错过了这个问题的重点
  • 你误会了我的问题,但没有人回答,我猜这是 chrome 控制台的错误,我在 chrome 的不同窗口中运行相同的代码,它显示不同的结果。但现在它可以工作了,也许,我无法执行属于另一个函数的函数;
猜你喜欢
  • 2021-11-18
  • 2022-08-18
  • 2013-05-11
  • 2011-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-07
相关资源
最近更新 更多