【问题标题】:How do I know when to use .bind() on a function in JS?我如何知道何时在 JS 中的函数上使用 .bind()?
【发布时间】:2019-08-29 16:21:19
【问题描述】:

(我知道this 的问题,但答案并不能完全告诉我我需要知道什么。)

我遇到过需要在 JavaScript 中的函数上使用 .bind() 以便将 this 或本地/类变量传递给函数的情况。但是,我仍然不知道什么时候需要它。

知道this 或局部/类变量何时在函数中可用或不可用的标准是什么?您对此有何推理?

例如:

  • 何时创建、包装或传递新的匿名 function() { }?
  • 当使用 class 成员函数、class getter/setter 函数或老式 prototype.function“成员函数”(作为类的函数)时?
  • 在全球范围内?
  • 在for 或forEach 循环或它们的任何变体中?
  • 在闭包外部或内部函数中?
  • 在Array.prototype.forEach.call()或[].forEach.call()等各种JS操作中?
  • 在各种JS库和脚本中,可能有自己自定义实现的东西?

我问的主要原因是要注意潜在的陷阱并避免依赖反复试验。

【问题讨论】:

  • 只有在你的函数代码使用this时才需要使用它,否则它不起作用。小例外适用,例如使用它进行柯里化,但让我们保持简单。
  • @dandavis 不,这正是我不想想要做的。反复试验不是编写代码的好方法,尤其是当它扩展时。我想了解发生了什么。
  • 要点:你并不经常需要它。一旦你掌握了基础知识,试错是唯一的学习方法。在 TDD 中,错误实际上是有目的的:您希望它在它工作之前不工作,以验证您的假设。您列出的所有问题的简短回答都是“否”,他们建议您实际上更需要了解this 在运行时是如何确定的(例如:与范围无关)。常见的“是”情况的简短列表是使用方法和事件处理程序到达触发元素(而不是 e.target)的承诺。

标签: javascript function scope this bind


【解决方案1】:

Mozilla 开发者网络在 this 上有一些很棒的文档,说明了不同的情况:

  1. Global context
  2. Function context
  3. using bind
  4. with arrow functions
  5. in object methods
  6. in an object constructor
  7. in DOM event handlers

查看链接以了解 this 在不同上下文中的工作原理,因此何时应使用 bind 为函数强制绑定不同的 this 上下文。

通常,bind 用于转移函数的“所有权”。具体来说,根据我的经验,在创建类之前使用它来强制将对象方法绑定到相关对象。它在使用箭头函数时也很有用,因为箭头函数有不同的上下文。

【讨论】:

  • 我会在 different contexts 中包含指向箭头函数的链接,但我是新贡献者,并且受限于我拥有的链接数量。
【解决方案2】:

您需要在以下情况下使用bind(或类似方法):

  • 函数是传统的(function 关键字)函数或方法(在 class 或对象字面量中),并且
  • 该函数的调用方式要么未明确设置this,要么将其设置为不正确的值

原因是对于传统的函数或方法,this 的值是由调用者设置的,不是函数本身的一部分。 (详情here和here。)

例如,考虑:

const obj = {
    method() {
        console.log(this === obj);
    }
};

现在,当我们执行obj.method() 时,我们使用语法(调用属性访问器操作的结果)来指定this 将是什么,所以:

obj.method();
// => true

但假设我们这样做:

const m = obj.method;

现在,只需调用m() 就会将this 设置为默认的this(严格模式下为undefined,松散模式下为全局对象):

m();
// => false

我们可以为调用显式设置this 的另一种方法是通过call(及其表亲apply):

m.call(obj);
// => true

一些调用回调的函数让您指定要使用的this。 forEach 确实,作为回调后的参数:

[1].forEach(m, obj);
//          ^  ^^^---- the value to use as `this` in callback
//           \-------- the callback to call
// => true

这是一个活生生的例子:

const obj = {
    method() {
        console.log(this === obj);
    }
};

obj.method();
// => true, `this` was set to `obj` because you did the call on the
// result of a property accessor
const m = obj.method;

m();
// => false, `this` was the default `this` used when `this` isn't
// specified explicitly via syntax or `call`

m.call(obj);
// => true, `this` was explicitly set via `call`

[1].forEach(m, obj);
// => true, `this` was explicitly set via `forEach`'s `thisArg` argument

所以任何时候你有一个函数(比如一个forEach的回调,或者一个事件处理程序),你需要bind或者类似的机制来确保使用正确的this。

这不适用于其他类型的函数,只是传统的(function 关键字)函数和方法(例如上面的obj.method)。箭头函数关闭 this 而不是使用调用者提供的函数,并且绑定函数(使用 bind 的结果)绑定了 this,因此忽略任何 @987654354 @由调用者提供。

【讨论】:

    【解决方案3】:

    感谢 T.J. Crowder 和 Zapparatus 的回答,他们提供了有用的信息。这 4 个答案/文章也很有帮助:1234

    然而,这些不是完全完整和/或非常冗长。所以我决定将我的所有发现与代码示例结合到一个答案中。


    在确定this 或局部/类变量是否在函数中可用时,需要考虑几个因素:

    • 函数的包含范围
    • 调用链中的直接前任
    • 函数是直接调用还是间接调用

    注意:还有严格模式(产生 undefined's 而不是 window 对象)和箭头函数(不会从包含范围更改 this)。


    以下是明确的规则:

    • 默认情况下,this 是全局对象,在浏览器世界中是window。
    • 在全局范围内的函数中,this 仍将是 window,它不会改变。
    • 在class 或函数类 (new function() { }) 内的成员函数内,在函数类的原型 (funcClass.prototype.func = function() { }) 内,在由具有 this 的相邻成员函数调用的函数内,或在映射到对象 ({ key: function() { } }) 或存储在数组 ([ function() { } ]) 中的函数,如果直接使用类/对象/数组作为调用链中的前导来调用该函数 (class.func()、this.func()、obj.func() 或 arr[0]()),this 指的是类/对象/数组实例。
    • 在任何闭包的内部函数(函数中的任何函数)内部、返回函数内部、以普通变量引用作为调用链中的直接前身调用的函数内部(无论它实际位于何处!),或在间接调用的函数内部(即传递给函数(例如.forEach(function() { }))或设置为处理事件),this 恢复为window 或调用者可能已将其绑定到(例如,事件可能会将其绑定到触发对象实例)。
      • 有……但是……有一个例外……:如果在 class 的成员函数中(并且只有 class,而不是函数类),如果其中的函数丢失了它的this 上下文(例如,作为闭包的内部函数),它变为 undefined,而不是 window...

    这是一个JSFiddle 和一堆代码示例:

    outputBox = document.getElementById("outputBox");
    
    function print(printMe = "") {
    	outputBox.innerHTML += printMe;
    }
    
    function printLine(printMe = "") {
    	outputBox.innerHTML += printMe + "<br/>";
    }
    
    var someVar = "someVar";
    
    function func(who) {
    	printLine("Outer func (" + who + "): " + this);
      var self = this;
      (function() {
      	printLine("Inner func (" + who + "): " + this);
        printLine("Inner func (" + who + ") self: " + self);
      })();
    }
    func("global");
    printLine();
    func.call(someVar, "someVar");
    
    printLine();
    
    function funcTwo(who) {
    	printLine("Outer funcTwo (" + who + "): " + this);
      var self = this;
      return function funcThree() {
      	printLine("Inner funcThree (" + who + "): " + this);
        printLine("Inner funcThree (" + who + ") self: " + self);
      };
    }
    funcTwo("global")();
    printLine();
    f = funcTwo("global f");
    f();
    printLine();
    funcTwo.call(someVar, "someVar")();
    
    printLine();
    
    object = {
      func: function(who) {
        printLine("Object outer (" + who + "): " + this);
        var self = this;
        (function() {
          printLine("Object inner (" + who + "): " + this);
          printLine("Object inner (" + who + ") self: " + self);
        })();
      }
    }
    object.func("good");
    printLine();
    bad = object.func;
    bad("bad");
    
    printLine();
    
    function funcClass(who) {
    	printLine("funcClass (" + who + "): " + this);
    }
    funcClass.prototype.func = function() {
    	printLine("funcClass.prototype.func: " + this);
      self = this;
      (function() {
        printLine("funcClass.func inner: " + this);
        printLine("funcClass.func inner self: " + self);
      })();
    }
    fc = funcClass("bad");
    printLine();
    fc = new funcClass("good");
    fc.func("good");
    
    printLine();
    
    class classClass {
    	constructor() {
      	printLine("classClass constructor: " + this);
      }
      func() {
      	printLine("classClass.func: " + this);
        self = this;
        (function() {
        	printLine("classClass.func inner: " + this);
          printLine("classClass.func inner self: " + self);
        })();
      }
      funcTwo() {
      	this.func();
      }
    }
    cc = new classClass();
    cc.func();
    printLine();
    printLine("Calling funcTwo:");
    cc.funcTwo();
    
    printLine();
    
    [0].forEach(function(e) {
    	printLine("[0].forEach: " + this);
      printLine("[0].forEach someVar: " + someVar);
    });
    [0].forEach(function(e) {
    	printLine("[0].forEach with [0]: " + this);
    }, [0]);
    
    printLine();
    
    arr = [
    	function(who) {
      	printLine("Array (" + who + "): " + this);
      },
      1,
      10,
      100
    ];
    arr[0]("good");
    arrFunc = arr[0];
    arrFunc("bad");
    
    printLine();
    
    var button = document.getElementById("button");
    button.onclick = function() {
    	printLine("button: " + this);
    }
    button.click();
    button.onclick = func;
    button.click();
    
    setTimeout(function() {
    	printLine();
    	printLine("setTimeout: " + this);
      printLine("setTimeout someVar: " + someVar);
    }, 0);
    
    setTimeout(fc.func, 0);
    setTimeout(cc.func, 0);
    <input id="button" type="button" value="button"/>
    <br/><br/>
    <div id="outputBox" />

    结论:是的,这很简单。

    【讨论】:

      猜你喜欢
      • 2015-11-30
      • 2021-11-07
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 2020-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多