我已经知道了,apply并且call是类似的函数集this(函数的上下文)。
apply
call
this
区别在于我们发送参数的方式(手动vs数组)
题:
但是什么时候应该使用该 bind()方法?
bind()
var obj = { x: 81, getX: function() { return this.x; } }; alert(obj.getX.bind(obj)()); alert(obj.getX.call(obj)); alert(obj.getX.apply(obj));
.bind()当你希望稍后在特定上下文中调用该函数时使用,该事件在事件中很有用。当你想立即调用该函数并修改上下文时,请使用.call()或.apply()。
.bind()
.call()
.apply()
调用/应用立即调用该函数,而bind返回一个函数,该函数在以后执行时将具有用于调用原始函数的正确上下文集。这样,你可以在异步回调和事件中维护上下文。
我经常这样做:
function MyObject(element) { this.elm = element; element.addEventListener('click', this.onClick.bind(this), false); }; MyObject.prototype.onClick = function(e) { var t=this; //do something with [t]... //without bind the context of this function wouldn't be a MyObject //instance as you would normally expect. };
我在Node.js中将它广泛用于异步回调,我想为其传递成员方法,但仍希望上下文成为启动异步操作的实例。
Node.js
一个简单,简单的bind实现是:
Function.prototype.bind = function(ctx) { var fn = this; return function() { fn.apply(ctx, arguments); }; };
它还有更多的功能(就像传递其他args一样),但是你可以阅读更多有关它的内容,并查看MDN上的实际实现。
希望这可以帮助。