no-extra-bind
禁止对 .bind() 进行不必要的调用
此规则报告的一些问题可通过 --fix 命令行 选项自动修复
bind() 方法用于创建具有特定 this 值的函数,并且可以选择性地将参数绑定到特定值。当用于指定 this 的值时,确保函数在其函数体中实际使用了 this 是很重要的。例如:
🌐 The bind() method is used to create functions with specific this values and, optionally, binds arguments to specific values. When used to specify the value of this, it’s important that the function actually uses this in its function body. For example:
const boundGetName = (function getName() {
return this.name;
}).bind({ name: "ESLint" });
console.log(boundGetName()); // "ESLint"
这段代码是一个使用 bind() 设置 this 值的良好示例。
🌐 This code is an example of a good use of bind() for setting the value of this.
有时在代码维护过程中,函数体中的 this 值会被移除。在这种情况下,你可能会得到一个对 bind() 的调用,但它不会完成任何操作:
🌐 Sometimes during the course of code maintenance, the this value is removed from the function body. In that case, you can end up with a call to bind() that doesn’t accomplish anything:
// useless bind
const boundGetName = (function getName() {
return "ESLint";
}).bind({ name: "ESLint" });
console.log(boundGetName()); // "ESLint"
在这段代码中,对 this 的引用已被移除,但 bind() 仍然在使用。在这种情况下,bind() 是不必要的开销(并且会影响性能),可以安全移除。
🌐 In this code, the reference to this has been removed but bind() is still used. In this case, the bind() is unnecessary overhead (and a performance hit) and can be safely removed.
规则详情
🌐 Rule Details
此规则旨在避免不必要地使用 bind(),因此每当一个立即调用的函数表达式(IIFE)使用 bind() 且没有适当的 this 值时,会发出警告。此规则不会标记包含函数参数绑定的 bind() 使用情况。
🌐 This rule is aimed at avoiding the unnecessary use of bind() and as such will warn whenever an immediately-invoked function expression (IIFE) is using bind() and doesn’t have an appropriate this value. This rule won’t flag usage of bind() that includes function argument binding.
注意: 箭头函数的 this 值永远不能使用 bind() 设置。此规则将箭头函数中所有使用 bind() 的情况标记为问题
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
/*eslint no-extra-bind: "error"*/
const x = function () {
foo();
}.bind(bar);
const y = (() => {
foo();
}).bind(bar);
const z = (() => {
this.foo();
}).bind(bar);
const a = function () {
(function () {
this.foo();
}());
}.bind(bar);
const b = function () {
function foo() {
this.bar();
}
}.bind(baz);
符合此规则的正确代码示例:
🌐 Examples of correct code for this rule:
/*eslint no-extra-bind: "error"*/
const x = function () {
this.foo();
}.bind(bar);
const y = function (a) {
return a + 1;
}.bind(foo, bar);
选项
🌐 Options
此规则没有选项。
🌐 This rule has no options.
何时不使用
🌐 When Not To Use It
如果你不关心对 bind() 的不必要调用,你可以放心地禁用这条规则。
🌐 If you are not concerned about unnecessary calls to bind(), you can safely disable this rule.
版本
此规则是在 ESLint v0.8.0 中引入。