JavaScript绑定对象字面量方法无法工作

4
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

})();

然而,如果使用“call”而不是“bind”
 ob.bind_part.call(t); //THIS WORKS

它能工作吗?

为什么绑定(bind)不起作用呢?有什么想法吗?

谢谢。

3个回答

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 不用了,答案里已经嵌入了一个测试 :) 点击“运行代码片段”并检查您的控制台。 - Ruan Mendes

0

.bind()方法不会改变函数本身,而是返回一个新的函数。你没有对返回值进行任何操作。以下代码可以正常工作:

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

0

.bind() 返回一个新的函数,你需要将其赋值回调用对象。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接