简体   繁体   English

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

[英]Javascript bind on object literal methods not working

The bind method does not transfer the 't' variable as the new 'this' keyword to the "ob.bind_part()' object literal function? 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 })(); 

However, instead of bind if 'call' is used 但是,如果使用'call',则不使用bind

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

it works? 有用?

any idea why bind does not work? 任何想法为什么绑定不起作用?

thanks 谢谢

Function.bind returns a new function, you have to assign it to obj.bind_part 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" })(); 

The .bind() method does not mutate a function, instead it returns a new one. .bind()方法不会改变函数,而是返回一个新函数。 You're not doing anything with the return value. 你没有对返回值做任何事情。 The following would work: 以下将有效:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM