wrap-iife
您可以立即调用函数表达式,但不能调用函数声明。创建立即调用函数表达式 (IIFE) 的一种常见技术是将函数声明括在括号中。开头的括号会导致包含的函数被解析为表达式,而不是声明。
js
// function expression could be unwrapped
var x = function () { return { y: 1 };}();
// function declaration must be wrapped
function () { /* side effects */ }(); // SyntaxError规则详细信息
此规则要求所有立即调用函数表达式都用括号括起来。
选项
此规则有两个选项,一个字符串选项和一个对象选项。
字符串选项
"outside"强制始终包装调用表达式。默认值为"outside"。"inside"强制始终包装函数表达式。"any"强制始终包装,但允许两种风格。
对象选项
"functionPrototypeMethods": true另外强制包装使用.call和.apply调用的函数表达式。默认值为false。
outside
针对默认 "outside" 选项的不正确代码示例
js
/*eslint @stylistic/js/wrap-iife: ["error", "outside"]*/
var x = function () { return { y: 1 };}(); // unwrapped
var x = (function () { return { y: 1 };})(); // wrapped function expression incorrect
针对默认 "outside" 选项的正确代码示例
js
/*eslint @stylistic/js/wrap-iife: ["error", "outside"]*/
var x = (function () { return { y: 1 };}()); // wrapped call expression correct
inside
针对 "inside" 选项的不正确代码示例
js
/*eslint @stylistic/js/wrap-iife: ["error", "inside"]*/
var x = function () { return { y: 1 };}(); // unwrapped
var x = (function () { return { y: 1 };}()); // wrapped call expression incorrect
针对 "inside" 选项的正确代码示例
js
/*eslint @stylistic/js/wrap-iife: ["error", "inside"]*/
var x = (function () { return { y: 1 };})(); // wrapped function expression correct
any
针对 "any" 选项的不正确代码示例
js
/*eslint @stylistic/js/wrap-iife: ["error", "any"]*/
var x = function () { return { y: 1 };}(); // unwrapped incorrect
针对 "any" 选项的正确代码示例
js
/*eslint @stylistic/js/wrap-iife: ["error", "any"]*/
var x = (function () { return { y: 1 };}()); // wrapped call expression
var x = (function () { return { y: 1 };})(); // wrapped function expression correct
functionPrototypeMethods
针对此规则使用 "inside", { "functionPrototypeMethods": true } 选项的不正确代码示例
js
/* eslint @stylistic/js/wrap-iife: [2, "inside", { functionPrototypeMethods: true }] */
var x = function(){ foo(); }()
var x = (function(){ foo(); }())
var x = function(){ foo(); }.call(bar)
var x = (function(){ foo(); }.call(bar)) incorrect
针对此规则使用 "inside", { "functionPrototypeMethods": true } 选项的正确代码示例
js
/* eslint @stylistic/js/wrap-iife: [2, "inside", { functionPrototypeMethods: true }] */
var x = (function(){ foo(); })()
var x = (function(){ foo(); }).call(bar) correct