Javascript绑定对象文字方法不起作用

时间:2015-04-08 11:09:41

标签: javascript bind

绑定方法不会传输''变量作为新的'这个' " 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

它有效吗?

任何想法为什么绑定不起作用?

感谢

3 个答案:

答案 0 :(得分: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"

})();




答案 1 :(得分:0)

.bind() method不会改变函数,而是返回一个新函数。你没有对返回值做任何事情。以下方法可行:

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

答案 2 :(得分:0)

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

ob.bind_part = ob.bind_part.bind(t);
相关问题