如何简洁地分配和立即调用函数变量? [英] How to concisely assign and immediately invoke a function variable?
问题描述
以下是在闭包中定义一个匿名函数的方法,调用函数并忘记它:
( function(){do stuff;})();
这用于在不向脚本添加批量的情况下保持有限的作用域(IIFE:立即调用的函数表达式)。
如果你希望立即执行一个函数,同时保留将来使用的函数,如下所示:
var doThing;
(doThing = function(){do stuff;})();
这适用于我测试过的浏览器(Chrome,FF,IE8,IE10),但是这个不通过JSLint(Bad Invocation)。这样做是否存在兼容性问题?
有没有一种方法可以达到这个目的?JSLint好心?
如果传递jslint是绝对必要的,那么:
var doThing ;
(doThing = function(){do stuff;})。call();
应该完成这项工作。
Edit
在 .call
var doThing;
(doThing = function(param1,param2){'do stuff';})。call(this,arg1,arg2);
The following is a method for defining an anonymous function within a closure, invoke the function, and forget it:
(function () { "do stuff"; })();
This is used to maintain a limited scope without adding bulk to the script (IIFE: Immediately-Invoked Function Expression).
What if you're hoping to immediately execute a function, while still retaining the function for future use, like the following:
var doThing;
(doThing = function () { "do stuff"; })();
This works in the browsers I've tested (Chrome, FF, IE8, IE10), but this does not pass JSLint (Bad Invocation). Are there any compatibility issues with doing it this way?
Is there a way of accomplishing this that is looked kindly upon by JSLint?
If passing jslint is absolutely necessary then:
var doThing;
(doThing = function () { "do stuff"; }).call();
should do the job.
Edit
For passing params during .call
var doThing;
(doThing = function (param1, param2) { 'do stuff'; }).call(this, arg1, arg2);
这篇关于如何简洁地分配和立即调用函数变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!