'self = this'vs apply或bind?(骨干)

Ken*_*ore 3 javascript backbone.js underscore.js

通常在我的Backbone代码中,我遇到了一些情况,我会将一个闭包传递给某个函数并丢失'this'的上下文.

我的解决方案已经有一段时间了,我做过其他人做过的事情:

var self = this;

this.deferred.done(function () {
    self.render();
});
Run Code Online (Sandbox Code Playgroud)

或者实际上我切换到了_this = this,但那不是重点.它有效,但感觉很难看,我有时必须经常这样做.所以我试图想出一个更好的方法来做到这一点.我知道我可以这样做:

this.deferred.done(function () {
    this.render();
}.apply(this));
Run Code Online (Sandbox Code Playgroud)

我想我也可以使用Underscore来做到这一点:

this.deferred.done(_.bind(function () {
    self.render();
}, this));
Run Code Online (Sandbox Code Playgroud)

这个apply方法看起来最简洁,但我觉得它有副作用(我只是不知道它是什么).

编辑:

看看这个JSbin,我使用的应用类似于我提到的:http://jsbin.com/qobumu/edit?js,console

它工作,但它同时抛出一个错误.如果我更改applybind,它可以工作,不会抛出错误.

Tou*_*ffy 5

  • 函数 .bind是一种本机方法,除非你编写古老的浏览器,否则不需要下划线.正是@dandavis所说的:(this.deferred.done(this.render.bind(this))但请注意,bind它也可以绑定函数参数,而不仅仅是this)

  • 如果您实际编写的是尖端浏览器或node.js 4,则可以使用箭头函数,这些函数在this词汇上绑定到定义函数的范围内的任何内容,因此您可以编写: this.deferred.done(() => { this.render() });