no-extra-bind

禁止对 .bind() 进行不必要的调用

🔧 Fixable

此规则报告的一些问题可通过 --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:

var 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
var 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.

注意:箭头函数永远不能使用 bind() 设置它们的 this 值。此规则将所有使用箭头函数的 bind() 标记为问题

¥Note: Arrow functions can never have their this value set using bind(). This rule flags all uses of bind() with arrow functions as a problem

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint no-extra-bind: "error"*/

var x = function () {
    foo();
}.bind(bar);

var x = (() => {
    foo();
}).bind(bar);

var x = (() => {
    this.foo();
}).bind(bar);

var x = function () {
    (function () {
      this.foo();
    }());
}.bind(bar);

var x = function () {
    function foo() {
      this.bar();
    }
}.bind(baz);

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint no-extra-bind: "error"*/

var x = function () {
    this.foo();
}.bind(bar);

var x = function (a) {
    return a + 1;
}.bind(foo, bar);

何时不使用

¥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 中引入。

进阶读物

资源

ESLint 中文网
粤ICP备13048890号