将新函数带入闭包

用户7951676

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

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

JavaScript 使用词法作用域帽子提示 deceze)。作用域由函数的定义位置决定,而不是由它的传递位置或调用位置决定。

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

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

这是一种常见的设计模式。例如,请参阅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()接受一个参数,该参数提供它将要处理的数据。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章