
no-extra-bind
禁用不必要的 .bind()
调用
🔧 可修复
此规则报告的一些问题可以通过 --fix
命令行 选项自动修复
bind()
方法用于创建具有特定 this
值和(可选)绑定到特定值的参数的函数。当用于指定 this
的值时,重要的是函数实际上在其函数体中使用 this
。例如
var boundGetName = (function getName() {
return this.name;
}).bind({ name: "ESLint" });
console.log(boundGetName()); // "ESLint"
此代码是 bind()
用于设置 this
值的良好用例示例。
有时在代码维护过程中,this
值会从函数体中移除。在这种情况下,您最终可能会调用 bind()
,但它没有任何作用
// useless bind
var boundGetName = (function getName() {
return "ESLint";
}).bind({ name: "ESLint" });
console.log(boundGetName()); // "ESLint"
在此代码中,对 this
的引用已被删除,但仍在使用 bind()
。在这种情况下,bind()
是不必要的开销(和性能损失),可以安全地移除。
规则详情
此规则旨在避免不必要地使用 bind()
,因此,每当立即调用函数表达式 (IIFE) 使用 bind()
且没有适当的 this
值时,都会发出警告。此规则不会标记包含函数参数绑定的 bind()
用法。
注意: 箭头函数永远无法使用 bind()
设置其 this
值。此规则标记所有将 bind()
与箭头函数一起使用的情况,都视为问题
此规则的错误代码示例
在 Playground 中打开
/*eslint no-extra-bind: "error"*/
var x = function () {
foo();
}.(bar);
var x = (() => {
foo();
}).(bar);
var x = (() => {
this.foo();
}).(bar);
var x = function () {
(function () {
this.foo();
}());
}.(bar);
var x = function () {
function foo() {
this.bar();
}
}.(baz);
此规则的正确代码示例
在 Playground 中打开
/*eslint no-extra-bind: "error"*/
var x = function () {
this.foo();
}.bind(bar);
var x = function (a) {
return a + 1;
}.bind(foo, bar);
何时不使用
如果您不关心不必要的 bind()
调用,您可以安全地禁用此规则。
版本
此规则在 ESLint v0.8.0 中引入。
延伸阅读

