简体   繁体   English

作为参数传递的javascript命名函数的范围是什么

[英]What's the scope of javascript named function, passed as parameter

I've work with some framework & even wrote some libraries for my own purpose. 我已经使用了一些框架,甚至为自己的目的编写了一些库。 I now working at implementation of an AngularJs router... And looked again at DI of angular: 我现在正在研究AngularJs路由器的实现...并再次查看angular的DI:

  1. [...String, Function] [...字符串,函数]
  2. function .$inject function 。$ inject

For long I've been using the first syntax. 长期以来,我一直在使用第一种语法。 Now while testing my router, I wanted to see the behaviour if it differs for both syntaxes and how to handle this, but... 现在,在测试路由器时,我想看看行为是否在语法和如何处理方面都不同,但是...

First Hand 第一手

module.controller(function SampleController()
{
});
// Since it's and `invokelater...` function which is called right away,
SampleController.$inject = [/** my component dependencies **/]

See my face when I faced: 当我面对时看到我的脸:

ReferenceError: SampleController is not defined ReferenceError:未定义SampleController

The Other Hand 另一方面

I consider it unclean to write: 我认为写不干净:

function SampleController()
{
}
SampleController.$inject = [];
moddule.$inject = [];

So Finally 所以最后

I know it won't work. 我知道这行不通。 Why? 为什么? - That's my question. -这是我的问题。

Why? 为什么?

We have been taught that module , class , method / functions , some for loop, if ... else create new scope. 我们被教导说moduleclassmethod / functions ,一些for循环, if ... else创建新的作用域。

Never have I read something like: 我从没读过类似的内容:

function's parameters are evaluated in their own scope 函数的参数在其自身范围内进行评估

Please Tell Me 请告诉我

Thanks! 谢谢!

Named function expressions only create a matching variable in their own scope (which is useful for calling the function recursively). 命名函数表达式仅在它们自己的范围内创建匹配变量(这对于递归调用函数很有用)。

They create nothing in the scope of the function that holds them. 它们在容纳它们的功能范围内不创建任何内容。

When you pass it as a function argument, then the variable you pass it into is scoped to the function call. 当您将其作为函数参数传递时,传递给它的变量的作用域为函数调用。 ie function function_you_pass_the_function_to(someFunction) { } scopes the someFunction variable to itself. function function_you_pass_the_function_to(someFunction) { }someFunction变量的作用域someFunction在其自身范围内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM