[英]Assign and execute Javascript function simultaneously
Is there a more elegant way of writing something like this, where myFunction is asigned to the function func but func is also executed during the assignment? 是否有一种更优雅的方式来编写这样的东西,其中myFunction与函数func一致,但func也在赋值期间执行?
var myFunction = (function(){
var func = function(){
console.log('hello world');
};
func();
return func;
})();
...
myFunction();
var myFunction = (function func(){
console.log('hello world');
return func;
})();
You can name your anonymous function. 您可以命名您的匿名函数。 This name will only be accessible inside of the function itself, though. 但是,此名称只能在函数本身内部访问。
Your core statement is this 你的核心陈述是这样的
var <name> = (<functionExpression>)();
I don't see how this could be more elegant. 我不知道这怎么会更优雅。
Assignments expressions return the assigned value, but you have to declare the variable separately so you still have to repeat the identifier: 赋值表达式返回指定的值,但您必须单独声明该变量,因此您仍然必须重复该标识符:
var outer;
(outer = function() {
var inner;
return (inner = function() {
print('hello world');
})(), inner;
})();
outer();
That said if I saw this code from a coworker I'd whap him with a rolled up newspaper. 那就是说,如果我从一位同事那里看到这个代码,我会用卷起的报纸给他打发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.