首页 文章

使用JavaScript 'bind'方法

提问于
浏览
481

bind() 在JavaScript中有什么用?

13 回答

  • 3

    Bind创建一个新函数,将 this 设置为传递给 bind() 的第一个参数 .

    这是一个示例,演示如何使用 bind 传递具有正确 this 的成员方法:

    var Button = function(content) { 
      this.content = content;
    };
    Button.prototype.click = function() {
      console.log(this.content + ' clicked');
    };
    
    var myButton = new Button('OK');
    myButton.click();
    
    var looseClick = myButton.click;
    looseClick(); // not bound, 'this' is not myButton - it is the global object
    
    var boundClick = myButton.click.bind(myButton);
    boundClick(); // bound, 'this' is myButton
    

    打印出来:

    OK clicked
    undefined clicked
    OK clicked
    

    您还可以在第一个( this )参数之后添加额外参数,并且 bind 将这些值传递给原始函数 . 您稍后传递给绑定函数的任何其他参数将在绑定参数之后传入:

    // Example showing binding some parameters
    var sum = function(a, b) {
      return a + b;
    };
    
    var add5 = sum.bind(null, 5);
    console.log(add5(10));
    

    打印出来:

    15
    

    有关更多信息和交互式示例,请查看JavaScript Function bind .

    更新:ECMAScript 2015增加了对 => 功能的支持 . => 函数更紧凑,不会将 this 指针从其定义范围更改,因此您可能不需要经常使用 bind() . 例如,如果您希望第一个示例中的 Button 上的函数将 click 回调连接到DOM事件,则以下是执行此操作的所有有效方法:

    Button.prototype.hookEvent(element) {
      // Use bind() to ensure 'this' is the 'this' inside click()
      element.addEventListener('click', this.click.bind(this));
    };
    

    要么:

    Button.prototype.hookEvent(element) {
      // Use a new variable for 'this' since 'this' inside the function
      // will not be the 'this' inside hookEvent()
      var me = this;
      element.addEventListener('click', function() { me.click() });
    }
    

    要么:

    Button.prototype.hookEvent(element) {
      // => functions do not change 'this', so you can use it directly
      element.addEventListener('click', () => this.click());
    }
    
  • 148

    bind允许 -

    • 将"this"的值设置为特定对象 . 这变得非常有用,因为有时this不是预期的 .

    • 重用方法

    • 咖喱一个功能

    例如,您可以扣除每月的俱乐部费用

    function getMonthlyFee(fee){
      var remaining = this.total - fee;
      this.total = remaining;
      return this.name +' remaining balance:'+remaining;
    }
    

    现在,您希望将此功能重新用于其他俱乐部会员 . 请注意,每月费用因会员而异 .

    让我们假设雷切尔的余额为500,每月会员费为90 .

    var rachel = {name:'Rachel Green', total:500};
    

    现在,创建一个可以反复使用的功能,每月从她的帐户中扣除费用

    //bind
    var getRachelFee = getMonthlyFee.bind(rachel, 90);
    //deduct
    getRachelFee();//Rachel Green remaining balance:410
    getRachelFee();//Rachel Green remaining balance:320
    

    现在,相同的getMonthlyFee函数可以用于具有不同会员费的另一个成员 . 例如,Ross Geller的余额为250,月费为25

    var ross = {name:'Ross Geller', total:250};
    //bind
    var getRossFee = getMonthlyFee.bind(ross, 25);
    //deduct
    getRossFee(); //Ross Geller remaining balance:225
    getRossFee(); //Ross Geller remaining balance:200
    
  • 7

    bind() 的最简单用法是创建一个函数,无论它如何调用,都使用特定的 this 值调用 .

    x = 9;
    var module = {
        x: 81,
        getX: function () {
            return this.x;
        }
    };
    
    module.getX(); // 81
    
    var getX = module.getX;
    getX(); // 9, because in this case, "this" refers to the global object
    
    // create a new function with 'this' bound to module
    var boundGetX = getX.bind(module);
    boundGetX(); // 81
    

    有关更多信息,请参阅此链接

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

  • 63

    the MDN docs开始 Function.prototype.bind()

    bind()方法创建一个新函数,在调用时,将其this关键字设置为提供的值,并在调用新函数时提供任何前面提供的给定参数序列 .

    那是什么意思?!

    好吧,让我们看一个如下所示的函数:

    var logProp = function(prop) {
        console.log(this[prop]);
    };
    

    现在,让我们看一个看起来像这样的对象:

    var Obj = {
        x : 5,
        y : 10
    };
    

    我们可以将函数绑定到我们的对象,如下所示:

    Obj.log = logProp.bind(Obj);
    

    现在,我们可以在代码中的任何位置运行 Obj.log

    Obj.log('x'); // Output : 5
    Obj.log('y'); // Output : 10
    

    这是有效的,因为我们将 this 的值绑定到我们的对象 Obj .


    真正有趣的地方是,当你不仅为 this 绑定一个值,而且还为它的参数 prop 绑定:

    Obj.logX = logProp.bind(Obj, 'x');
    Obj.logY = logProp.bind(Obj, 'y');
    

    我们现在可以这样做:

    Obj.logX(); // Output : 5
    Obj.logY(); // Output : 10
    

    Obj.log 不同,我们不必传递 xy ,因为我们在进行绑定时传递了这些值 .

  • 1

    我将在理论上和实践上解释绑定

    在javascript中绑定是一个方法 - Function.prototype.bind . bind是一种方法 . 它被称为函数原型 . 此方法创建一个函数,其主体类似于调用它的函数,但'this'指的是传递给bind方法的第一个参数 . 它的语法是

    var bindedFunc = Func.bind(thisObj,optionsArg1,optionalArg2,optionalArg3,...);
    

    例: -

    var checkRange = function(value){
          if(typeof value !== "number"){
                  return false;
          }
          else {
             return value >= this.minimum && value <= this.maximum;
          }
      }
    
      var range = {minimum:10,maximum:20};
    
      var boundedFunc = checkRange.bind(range); //bounded Function. this refers to range
      var result = boundedFunc(15); //passing value
      console.log(result) // will give true;
    
  • 11

    bind()方法创建一个新的函数实例,该值绑定到传递给bind()的值 . 例如:

    window.color = "red"; 
       var o = { color: "blue" }; 
       function sayColor(){ 
           alert(this.color); 
       } 
       var objectSayColor = sayColor.bind(o); 
       objectSayColor(); //blue
    

    这里,通过调用bind()并传入对象o,从sayColor()创建一个名为objectSayColor()的新函数 . objectSayColor()函数具有等于o的this值,因此即使作为全局调用,调用该函数也会导致显示字符串“blue” .

    参考:Nicholas C. Zakas - 面向WEB开发人员的专业JAVASCRIPT®

  • 5

    变量具有本地和全球范围 . 假设我们有两个具有相同名称的变量 . 一个是全局定义的,另一个是在函数闭包内定义的,我们想要得到函数闭包内的变量值 . 在这种情况下,我们使用这个bind()方法 . 请看下面的简单示例:

    var x = 9;    // this refers to global "window" object here in the browser
    var person = {
      x: 81,
      getX: function() { return this.x; }
    };
    var y = person.getX; // It will return 9, because it will call global value of x(var x=9).
    
    var x2 = y.bind(person); // It will return 81, because it will call local value of x, which is defined in the object called person(x=81).
    
    document.getElementById("demo1").innerHTML = y(); 
    document.getElementById("demo2").innerHTML = x2();
    
    <!DOCTYPE html>
    <html>
    <body>
    <p id="demo1">0</p>
    <p id="demo2">0</p>
    </body>
    </html>
    
  • -1

    通过将参数绑定到值来创建新函数

    bind 方法从中创建一个新函数另一个函数,其中一个或多个参数绑定到特定值,包括隐式 this 参数 .

    部分申请

    这是partial application的一个例子 . 通常我们提供一个函数及其所有参数,它们产生一个值 . 这称为功能应用程序 . 我们将函数应用于它的参数 .

    高阶函数(HOF)

    部分应用程序是higher order function(HOF)的示例,因为它产生具有较少参数的新函数 .

    绑定多个参数

    您可以使用 bind 将具有多个参数的函数转换为新函数 .

    function multiply(x, y) { 
        return x * y; 
    }
    
    let multiplyBy10 = multiply.bind(null, 10);
    console.log(multiplyBy10(5));
    

    从实例方法转换为静态函数

    在最常见的用例中,当使用一个参数调用时, bind 方法将创建一个将 this 值绑定到特定值的新函数 . 实际上,这会将实例方法转换为静态方法 .

    function Multiplier(factor) { 
        this.factor = factor;
    }
    
    Multiplier.prototype.multiply = function(x) { 
        return this.factor * x; 
    }
    
    function ApplyFunction(func, value) {
        return func(value);
    }
    
    var mul = new Multiplier(5);
    
    // Produces garbage (NaN) because multiplying "undefined" by 10
    console.log(ApplyFunction(mul.multiply, 10));
    
    // Produces expected result: 50
    console.log(ApplyFunction(mul.multiply.bind(mul), 10));
    

    实现有状态回调

    以下示例显示如何使用 this 的绑定可以使对象方法充当可以轻松更新对象状态的回调 .

    function ButtonPressedLogger()
    {
       this.count = 0;
       this.onPressed = function() {
          this.count++;
          console.log("pressed a button " + this.count + " times");
       }
       for (let d of document.getElementsByTagName("button"))
          d.onclick = this.onPressed.bind(this);
    }
    
    new ButtonPressedLogger();
    
    <button>press me</button>
    <button>no press me</button>
    
  • 8

    摘要:

    bind() 方法将对象作为第一个参数并创建一个新函数 . 调用函数时,函数体中 this 的值将是作为 bind() 函数中的参数传入的对象 .

    无论如何,这在JS中是如何工作的

    javascript中 this 的值依赖于函数调用的对象 . The value of this always refers to the object left of the dot from where is the function is called . 在全局范围的情况下,这是 window (或 nodeJS 中的 global ) . 只有 callapplybind 才能以不同方式更改此绑定 . 下面是一个示例,说明this关键字的工作原理:

    let obj = {
      prop1: 1,
      func: function () { console.log(this); } 
    }
    
    obj.func();   // obj left of the dot so this refers to obj
    
    const customFunc = obj.func;  // we store the function in the customFunc obj
    
    customFunc();  // now the object left of the dot is window, 
                   // customFunc() is shorthand for window.customFunc()
                   // Therefore window will be logged
    

    如何使用绑定?

    绑定可以通过使用 this 将引用的固定对象来帮助克服 this 关键字的困难 . 例如:

    var name = 'globalName';
    
    const obj = {
      name: 'myName',
      sayName: function () { console.log(this.name);}
    }
    
    const say = obj.sayName; // we are merely storing the function the value of this isn't magically transferred
    
    say(); // now because this function is executed in global scope this will refer to the global var
    
    const boundSay = obj.sayName.bind(obj); // now the value of this is bound to the obj object
    
    boundSay();  // Now this will refer to the name in the obj object: 'myName'
    

    一旦函数绑定到特定的 this 值,我们就可以传递它,甚至将它放在其他对象的属性上 . this 的值将保持不变 .

  • 9

    如上所述, Function.bind() 允许您指定函数将执行的上下文(也就是说,它允许您传递 this 关键字将在函数体中解析的对象 .

    一些执行类似服务的类似工具包API方法:

    jQuery.proxy()

    Dojo.hitch()

  • 147
    /**
     * Bind is a method inherited from Function.prototype same like call and apply
     * It basically helps to bind a function to an object's context during initialisation 
     * 
     * */
    
    window.myname = "Jineesh";  
    var foo = function(){ 
      return this.myname;
    };
    
    //IE < 8 has issues with this, supported in ecmascript 5
    var obj = { 
        myname : "John", 
        fn:foo.bind(window)// binds to window object
    }; 
    console.log( obj.fn() ); // Returns Jineesh
    
  • 7

    bind函数使用与它调用的函数相同的函数体创建一个新函数 . 它使用this参数调用 . 为什么我们使用bind fun . :当每次创建一个新实例并且我们必须使用第一个初始实例时,我们使用bind fun.We不能覆盖绑定fun.simply它存储类的初始对象 .

    setInterval(this.animate_to.bind(this), 1000/this.difference);
    
  • 496

    bind是一个在java脚本原型中可用的函数,因为名称建议bind用于将函数调用绑定到您正在处理的上下文中,例如:

    var rateOfInterest='4%';
        var axisBank=
        {
        rateOfInterest:'10%',
        getRateOfInterest:function()
        {
        return this.rateOfInterest;
        }
        }
        axisBank.getRateOfInterest() //'10%' 
    
    
        let knowAxisBankInterest=axisBank.getRateOfInterest // when you want to assign the function call to a varaible we use this syntax
        knowAxisBankInterest(); // you will get output as '4%' here by default the function is called wrt global context
    
    let knowExactAxisBankInterest=knowAxisBankInterest.bind(axisBank);     //so here we need bind function call  to its local context
    
    
        knowExactAxisBankInterest() // '10%'
    

相关问题