从回调和内联自调用函数访问父函数变量 [英] Parent function variable access from callback and inline self invoking function

查看:52
本文介绍了从回调和内联自调用函数访问父函数变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信乍看之下,两个自调用函数都是相同的,只是它们之间的区别是,第一个是我传递回调函数,然后由arguments对象执行,而第二个是通过使函数自调用来做同样的事情.现在谈到访问第一个示例名称为" undefined "的父变量的问题,而在第二个示例中,它可以访问并给出输出" Nishant ",我无法确定知道它是如何工作的!

I believed at first look both self invoking function is same only difference between them is in first one I am passing callback function and then executing by arguments object while in second doing same thing by making function self invoking. Now come to points of accessing parent variable in first one example name is "undefined" while in second one example it's accessible and giving output "Nishant" I am not able to figure out how It's working!!

(function(){
    var name = "Nishant";
    arguments[0]();

})(function(){console.log(name);});

输出:(一个空字符串)

(function(){
  var name = "Nishant";
  (function(){console.log(name);})()
})();

输出:Nishant

推荐答案

我不知道它是如何工作的!

I am not able to figure out how It's working!!

JavaScript具有 词法范围.这意味着范围由在源代码中定义函数的位置确定(不同于动态范围,在动态范围在运行时调用函数时确定范围).

JavaScript has lexical scope. That means the scope is determined by where the functions are defined inside the source code (unlike dynamic scope, where the scope is determined when the functions are called at runtime).

让我们为您的函数添加一些名称,以便我们更轻松地引用它们:

Lets add some names to your functions so we can reference them more easily:

(function foo(){
    var name = "Nishant";
    arguments[0]();
})(function bar(){console.log(name);});

在这种情况下, bar 是在 foo 外部中定义的,因此无法访问在 foo .实际上,在创建 bar 的那一刻, foo 中的变量 name 甚至还不存在,因为 foo 尚未执行.
不内联定义时,可能更容易查看:

In this case bar is defined outside of foo and hence cannot have access to the variable defined inside of foo. In fact, at the moment bar is created, the variable name inside foo doesn't even exist yet, since foo hasn't been executed yet.
Maybe it's easier to see when you do not inline the definition:

function bar(){console.log(name);}

(function foo(){
    var name = "Nishant";
    arguments[0]();
})(bar);

这看起来可能更熟悉,我敢打赌您不会期望 bar 中的 name foo ,对吧?

This might look more familiar, and I bet you wouldn't expect that name inside bar has anything to do with name inside foo, right?

在另一种情况下,

(function foo(){
  var name = "Nishant";
  (function bar(){console.log(name);})()
})();

您在 foo bar inside 中定义了. name 也在 foo 内部,因此 bar 可以访问该变量(词法作用域+闭包).

you defined bar inside of foo. name is also inside foo and hence bar has access to that variable (lexical scope + closure).

这篇关于从回调和内联自调用函数访问父函数变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆