何时在JS中使用.bind() [英] When to use .bind() in JS

查看:194
本文介绍了何时在JS中使用.bind()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有大量关于如何使用 bind()的博客和帖子,以及它与 call() apply(),但 为什么我应该使用<$ c的例子很少$ c> bind()

There is a ton of blogs and posts about how to use bind() and how it's different than call() and apply(), but there is very little examples to when or why should I use bind()

我发现很多给出的例子非常罕见,例如:

I found many of the examples given are very uncommon occurrences such as this:

"use strict";

function Person(firstName, lastName){
  this.firstName = firstName
  this.lastName = lastName
}

Person.prototype.say = function(message){
  return '[' + this + ']: ' + this.firstName + ' ' + this.lastName + ' said: "' + message + '"'
}

Person.prototype.toString = function(){
  return '[Person]'
}

moe = new Person("Mo", "El")


func = moe.say.bind(moe)

console.log(func("asdasda"))

我不知道什么时候我想让函数等于某个其他变量并使用该变量而不是原始函数,更不用说该变量等于 Person 对象的实例的绑定。

I don't know when there is a time I want to make a function equal to some other variable and use that variable instead of the original function, let alone that variable is equal the binding of an instance of the Person object.

有什么好例子吗?

推荐答案

简而言之, .bind()返回一个新函数当调用时,将使用特定的值调用原始函数,并(可选)将一些新参数预先填充到参数列表中。

In a nutshell, .bind() returns a new function that when called will call the original function with a specific this value and (optionally) some new arguments preprended to the argument list.

.bind()用于需要传递回调(例如某种函数引用),但是你希望调用者用你的函数调用你的函数具体值。当您的函数实际上是一个方法并且您希望将值设置为特定对象时,这是最常见的,因此该方法将对该特定对象进行操作。如果您在这些情况下不使用 .bind(),则值将由调用者确定(不是你)如果调用者没有专门设置它,它将最终成为全局对象或(在严格模式下) undefined 。如果你传递的是一个依赖于这个的特定值的方法来完成它的工作,它将无法正确处理错误的这个值。

.bind() is used when you need to pass a callback (e.g. some sort of function reference), but you want the caller to call your function with a specific this value. This is most common when your function is actually a method and you want the this value set to be the a specific object so the method will operate on that specific object . If you don't use .bind() in those cases, then the this value will be determined by the caller (not you) and if the caller doesn't set it specifically, it will end up being the global object or (in strict mode) undefined. If what you were passing was a method that relies on a specific value of this in order to do its job, it would not work properly with the wrong this value.

所以,如果你想控制这个的值,那么你的回调被调用,你可以使用 .bind()。在内部, .bind()只是创建一个小的存根函数,它只记住传递它的这个值并调用你的使用 .apply()来设置值。 .bind()并不神奇,因为它也可以手动完成。

So, if you want to control the value of this when your callback is called, you can use .bind(). Internally, .bind() just creates a small stub function that just remembers the this value you pass it and calls your function with .apply() to set the this value. .bind() is not magic as it can be done manually too.

。 bind()还具有向函数添加额外参数的功能,因此,如果要添加超出回调正常调用者的参数,可以使用指定参数。 .bind()也是。它创建一个存根函数,它将添加这些额外的参数并设置这个值。

.bind() also has the capability to add extra arguments to the function so, if you want to add arguments beyond what the normal caller of the callback uses, you can specify those with .bind() too. It creates a stub function that will add these extra arguments and set the this value.

假设您有 Person 对象,并且想要将按钮挂钩到 .say()特定 Person 对象的方法。

Let's say you have your Person object and you want to hook a button up to the .say() method for a particular Person object.

<button id="talk">Talk</button>

并且,如果你试过这个javascript:

And, if you tried this javascript:

"use strict";
var bob = new Person("Bob", "Smith");
document.getElementById("talk").addEventListener("click", bob.say);

你会发现说()方法被调用,但它会丢失两件事。它将缺少正确的引用(将设置为按钮对象,因为这是addEventListener调用其回调的方式)它会错过说(消息)期望的论点。

What you would find is that the say() method is called, but it would be missing two things. It would be missing the right this reference (which would be set to the button object because that's how addEventListener calls its callbacks) and it would be missing the argument that say(message) expects.

所以,你可以自己解决这个问题使用您自己的存根函数,使用所有正确的参数调用 bob.say()

So, you could solve this yourself with your own stub function that calls bob.say() with all the right arguments:

"use strict";
var bob = new Person("Bob", "Smith");
document.getElementById("talk").addEventListener("click", function(e) {
    bob.say("Hello");
});

或者,您可以使用 .bind()

"use strict";
var bob = new Person("Bob", "Smith");
document.getElementById("talk").addEventListener("click", bob.say.bind(bob, "Hello"));






.bind()。它可以在javascript中完全模拟。事实上,这是来自MDN的polyfill:


There is no magic in .bind(). It can be entirely simulated in javascript. In fact, here's a polyfill for it from MDN:

if (!Function.prototype.bind) {
  Function.prototype.bind = function(oThis) {
    if (typeof this !== 'function') {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }

    var aArgs   = Array.prototype.slice.call(arguments, 1),
        fToBind = this,
        fNOP    = function() {},
        fBound  = function() {
          return fToBind.apply(this instanceof fNOP && oThis
                 ? this
                 : oThis,
                 aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
}

由于所有的错误检查,这可能看起来比较复杂,但是它实际上只返回一个新函数,它结合了两组参数,然后使用特定的这个值调用原始函数。

This may look more complicated than it is because of all the error checking, but it's really just return a new function that combines two sets of arguments and then calls the original function with a specific this value.

这篇关于何时在JS中使用.bind()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆