[英]'self = this' vs apply or bind? (Backbone)
Often in my Backbone code I come across situations where I would be passing a closure to some function and lose context of 'this'. 通常在我的Backbone代码中,我遇到了一些情况,我会将一个闭包传递给某个函数并丢失'this'的上下文。
My solution for some time had been to do what I had seen some others do: 我的解决方案已经有一段时间了,我做过其他人做过的事情:
var self = this;
this.deferred.done(function () {
self.render();
});
Or actually I switched to _this = this
, but that's beside the point. 或者实际上我切换到_this = this
,但这不是重点。 It works, but it feels ugly and I sometimes have to do it quite often. 它有效,但感觉很难看,我有时必须经常这样做。 So I'm trying to figure out a better way to do this. 所以我试图想出一个更好的方法来做到这一点。 I learned I could do this: 我知道我可以这样做:
this.deferred.done(function () {
this.render();
}.apply(this));
And I think I could also use Underscore to do this: 我想我也可以使用Underscore来做到这一点:
this.deferred.done(_.bind(function () {
self.render();
}, this));
The apply
method seems the most succinct but I feel like it has a side effect (I just don't know what it is yet). apply
方法似乎最简洁,但我觉得它有副作用(我只是不知道它是什么)。
Edit: 编辑:
Take a look at this JSbin where I use apply similar to as I mentioned: http://jsbin.com/qobumu/edit?js,console 看看这个JSbin,我使用的应用类似于我提到的: http ://jsbin.com/qobumu/edit?js,console
It works, yet it throws an error at the same time. 它工作,但它同时抛出一个错误。 If I change the apply
to bind
, it works and doesn't throw an error. 如果我将apply
更改为bind
,它可以工作并且不会抛出错误。
Function .bind is a native method, no need for underscore unless you're coding for antique browsers. 函数 .bind是一种本机方法,除非你编写古老的浏览器,否则不需要下划线。 Exactly what @dandavis said: this.deferred.done(this.render.bind(this))
(but note that bind
can also bind function arguments, not just this
) 正是@dandavis所说的: this.deferred.done(this.render.bind(this))
(但请注意, bind
也可以绑定函数参数,而不仅仅是this
)
if you're actually coding for cutting-edge browsers or node.js 4, you can use arrow functions which bind this
lexically to whatever it is in the scope where the function is defined, so you could write: this.deferred.done(() => { this.render() });
如果您实际编写的是尖端浏览器或node.js 4,则可以使用箭头函数将this
词汇绑定到定义函数的范围内的任何内容,因此您可以编写: this.deferred.done(() => { this.render() });
Those do different things. 那些做不同的事情。
// returns a function with `this` set to what you want.
_.bind(fn, this);
// or
fn.bind(this);
// EXECUTES the function with `this` set to what you want.
fn.apply(this);
So in your case it's not a callback at all. 所以在你的情况下,它根本不是回调。 When you use apply
you are executing the function when you think you are assigning the callback. 使用apply
时,如果您认为正在分配回调,则执行该功能。
This is why you use bind. 这就是你使用bind的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.