【问题标题】:Bring a new function into a closure将新函数带入闭包
【发布时间】:2023-04-05 12:13:01
【问题描述】:

我已经阅读了很多关于闭包的文章,并且我经常使用它们,但是我发现了一个我不理解的案例。 为什么我传递给测试的函数无法访问 hello 变量?它不应该在查看范围更改时找到它吗? 我的代码:

(function($){
    var hello="hello world"
    $.test=function(a){
        alert(hello+" 1")
        a()}
})(this)
test(function(){alert(hello+" 2")})

【问题讨论】:

  • 您似乎期望的是动态作用域(从调用者继承),但 Javascript 具有词法作用域(按书面形式继承)。跨度>
  • 请不要在标题中添加“已解决”,答案上的绿色勾号表示您找到了解决方案
  • 抱歉,我用的是屏幕阅读器,不知道

标签: javascript function scope closures


【解决方案1】:

JavaScript 使用 lexical scope帽子提示)。范围由函数定义的位置决定,而不是由函数的传递位置或调用位置决定。

如果你希望一个函数能够从它传递到的范围内访问变量中的数据,你需要定义它以便它接受一个参数,然后你需要传递数据。

"use strict";
(function($) {
  var hello = "hello world"
  $.test = function(a) {
    alert(hello + " 1")
    a(hello);
  }
})(this);
test(function(passed_data) {
  alert(passed_data + " 2")
});

这是一种常见的设计模式。例如见the Promise API

myFirstPromise.then((successMessage) => {
  // successMessage is whatever we passed in the resolve(...) function above.
  // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
  console.log("Yay! " + successMessage);
});

请注意传递给then() 的函数如何接受一个参数,该参数提供它将处理的数据。

【讨论】:

  • 谢谢,我会接受,但它说我要增重 5 分钟
猜你喜欢
  • 1970-01-01
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-31
  • 2022-01-18
相关资源
最近更新 更多