【问题标题】:Javascript bind on object literal methods not working对象文字方法上的Javascript绑定不起作用
【发布时间】:2015-04-08 11:09:40
【问题描述】:

bind 方法不会将 't' 变量作为新的 'this' 关键字传递给“ob.bind_part()” 对象字面量函数吗?

var ob = {

  "first": function() {
    console.log("first function");
    var t = "new bind";
    ob.bind_part.bind(t);
  },


  "bind_part": function() {
    console.log(this.toString());
  }

};


(function() {
  ob.first();

  ob.bind_part(); // returns the 'ob' object instead of the bind

})();

但是,如果使用“调用”而不是绑定

 ob.bind_part.call(t); //THIS WORKS

有效吗?

知道为什么绑定不起作用吗?

谢谢

【问题讨论】:

    标签: javascript bind


    【解决方案1】:

    Function.bind 返回一个新函数,你必须将它分配给obj.bind_part

    var ob = {
    
      "first": function() {
        console.log("first function");
        var t = "new bind";
        ob.bind_part = ob.bind_part.bind(t);
      },
    
    
      "bind_part": function() {
        console.log(this.toString());
      }
    
    };
    
    
    (function() {
      ob.first();
    
      ob.bind_part(); // returns "new bind"
    
    })();

    【讨论】:

    • @user3464127 不需要,答案中已经嵌入了一个测试:) 按“运行代码 sn-p”并检查您的控制台
    【解决方案2】:

    .bind() method 不会改变函数,而是返回一个新函数。您没有对返回值做任何事情。以下将起作用:

    ob.bind_part = ob.bind_part.bind(t);
    

    【讨论】:

      【解决方案3】:

      .bind() 返回一个新函数,您需要将其分配回调用对象。

      ob.bind_part = ob.bind_part.bind(t);
      

      【讨论】:

        猜你喜欢
        • 2018-05-03
        • 2013-12-28
        • 2020-01-23
        • 1970-01-01
        • 2023-03-28
        • 2012-06-20
        • 2015-07-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多