'self = this' vs 申请或绑定? (Backbone)
'self = this' vs apply or bind? (Backbone)
经常在我的 Backbone 代码中遇到这样的情况:我将闭包传递给某个函数并丢失 'this'.
的上下文
一段时间以来,我的解决方案一直是做我看到其他人做的事情:
var self = this;
this.deferred.done(function () {
self.render();
});
或者实际上我切换到 _this = this
,但这不是重点。它有效,但感觉很难看,有时我不得不经常这样做。所以我想找出一个更好的方法来做到这一点。我了解到我可以这样做:
this.deferred.done(function () {
this.render();
}.apply(this));
而且我想我也可以使用 Underscore 来做到这一点:
this.deferred.done(_.bind(function () {
self.render();
}, this));
apply
这个方法貌似最简洁,但我觉得它有一个副作用(我只是还不知道它是什么)。
编辑:
看看这个 JSbin,我在其中使用类似于我提到的应用:
http://jsbin.com/qobumu/edit?js,console
它有效,但同时抛出错误。如果我将 apply
更改为 bind
,它会起作用并且不会引发错误。
Function.bind 是一种本机方法,除非您正在为古董浏览器编码,否则不需要下划线。正如@dandavis 所说:this.deferred.done(this.render.bind(this))
(但请注意 bind
也可以绑定函数参数,而不仅仅是 this
)
如果您实际上是在为尖端浏览器或 node.js 4 编写代码,则可以使用箭头函数将 this
词法绑定到范围内的任何内容该函数已定义,因此您可以编写:
this.deferred.done(() => { this.render() });
它们做不同的事情。
// 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);
所以在你的情况下它根本不是回调。当您使用 apply
时,当您认为您正在分配回调时,您正在 执行 函数。
这就是你使用 bind 的原因。
经常在我的 Backbone 代码中遇到这样的情况:我将闭包传递给某个函数并丢失 'this'.
的上下文一段时间以来,我的解决方案一直是做我看到其他人做的事情:
var self = this;
this.deferred.done(function () {
self.render();
});
或者实际上我切换到 _this = this
,但这不是重点。它有效,但感觉很难看,有时我不得不经常这样做。所以我想找出一个更好的方法来做到这一点。我了解到我可以这样做:
this.deferred.done(function () {
this.render();
}.apply(this));
而且我想我也可以使用 Underscore 来做到这一点:
this.deferred.done(_.bind(function () {
self.render();
}, this));
apply
这个方法貌似最简洁,但我觉得它有一个副作用(我只是还不知道它是什么)。
编辑:
看看这个 JSbin,我在其中使用类似于我提到的应用: http://jsbin.com/qobumu/edit?js,console
它有效,但同时抛出错误。如果我将 apply
更改为 bind
,它会起作用并且不会引发错误。
Function.bind 是一种本机方法,除非您正在为古董浏览器编码,否则不需要下划线。正如@dandavis 所说:
this.deferred.done(this.render.bind(this))
(但请注意bind
也可以绑定函数参数,而不仅仅是this
)如果您实际上是在为尖端浏览器或 node.js 4 编写代码,则可以使用箭头函数将
this
词法绑定到范围内的任何内容该函数已定义,因此您可以编写:this.deferred.done(() => { this.render() });
它们做不同的事情。
// 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);
所以在你的情况下它根本不是回调。当您使用 apply
时,当您认为您正在分配回调时,您正在 执行 函数。
这就是你使用 bind 的原因。