【问题标题】:Understanding "Side Effects" in Javascript with Respect to First-class Functions了解 Javascript 中关于一流函数的“副作用”
【发布时间】:2017-06-01 00:47:38
【问题描述】:

我遇到了一个特别有趣的案例,我认为这是 Javascript 的副作用。

我正试图围绕范围以及函数是一等公民这一事实。如果我走在正确的轨道上,请告诉我,如果这是一个新手问题,请原谅我。

参考以下代码:

let mrGlobal = "mrGlobal";
let drSideEffect = function() {
   mrGlobal = "mrGlobal has been acting weird lately";
}

function main(firstClassFunction) {
   let mrGlobal = "mrGlobal: version 2.";
   firstClassFunction
   console.log(mrGlobal)                    //First console.log
}
main(drSideEffect());
console.log(mrGlobal)                      //Second console.log

对于第一个 consol.log,输出为:mrGlobal 版本 2。
在第二个 consol.log 的情况下,输出是:mrGlobal 最近表现得很奇怪

我最初认为这会导致 opppsite 行为(第一个 console.log 与第二个 console.log 切换)所以这个输出让我感到惊讶。我假设这是因为 javascript 中的函数绑定到声明它们的范围,而不是执行它们的范围 - 即使它们作为一等公民传递到该范围?

【问题讨论】:

标签: javascript scope first-class-functions


【解决方案1】:

首先,测试的一个小问题:你没有将函数drSideEffect传递给main;你调用它,然后传递它的返回值(什么都没有)。 firstClassFunctionundefined,而 firstClassFunction 在一行上本身就是空操作。相反,请在main 中调用它:

firstClassFunction();

并传递函数而不调用它:

main(drSideEffect);

不过,结果将是相同的,因为您是对的:函数继承了定义它们的作用域,而不是调用它们的作用域。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 2017-10-08
    • 2011-11-11
    • 1970-01-01
    相关资源
    最近更新 更多