[英]What are the usage scenarios or advantages of defining functions after the return expression
En example can be found in Twitter'a typeahead.js here : 恩例子可以在Twitter'a找到typeahead.js这里 :
function () {
// ...
return this.each(initialize);
function initialize() {
// ...
}
}
Questions: 问题:
Javascript has function based scope, which means that every thing defined inside a function is available from the first line, since the definition is "hoisted" by the complier. Javascript具有基于函数的作用域,这意味着在函数内部定义的所有内容都可以从第一行获得,因为定义是由编译器“提升”的。
That goes for both variable and function definitions - variable values however, are not available until after assignment. 这适用于变量和函数定义-但是,变量值直到分配后才可用。
You can read all about javascript scoping and hoisting here 您可以在此处阅读有关javascript作用域和提升的所有信息
This means that the function initialize
is available from the first line of the wrapping anonymous function. 这意味着可以从包装匿名函数的第一行获得函数initialize
。
There is no real reason, and no advantages, for doing it that way, unless you count the code structure as an advantage. 这样做没有任何真正的理由,也没有优势,除非您将代码结构视为优势。
Personally I don't see any reason to do this. 就我个人而言,我没有任何理由这样做。 For me even it looks a little bit weird. 对我来说,甚至看起来有点奇怪。 Martin is right. 马丁是对的。 You should be careful, because the defined variables are not accessible like functions. 您应该小心,因为不能像函数一样访问已定义的变量。 For example this doesn't work: 例如,这不起作用:
var getValue = function(func) {
return func();
}
var f = function() {
return getValue(now);
var now = function() {
return 10;
}
}
alert(f());
However, this works: 但是,这可行:
var getValue = function(func) {
return func();
}
var f = function() {
return getValue(now);
function now() {
return 10;
}
}
alert(f());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.