将一个新函数带入一个闭包

use*_*676 1 javascript closures scope function

我已经阅读了很多关于闭包的内容,我经常使用它们但是我发现了一个我不理解的案例.为什么我的函数不能访问hello变量我正在测试?它不应该通过范围变化找到它吗?我的代码:

(function($){
    var hello="hello world"
    $.test=function(a){
        alert(hello+" 1")
        a()}
})(this)
test(function(){alert(hello+" 2")})
Run Code Online (Sandbox Code Playgroud)

Que*_*tin 6

JavaScript使用词法范围(帽子提示去骗).范围取决于函数的定义位置,而不是通过它的位置或调用函数的位置.

如果希望函数能够从传递给它的作用域中访问变量中的数据,则需要定义它以使其接受参数,然后需要传递数据.

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

这是一种常见的设计模式.例如,请参阅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);
});
Run Code Online (Sandbox Code Playgroud)

注意传递给函数的方法是如何then()获取一个参数,该参数提供了它将要处理的数据.