Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ';self=this';vs应用还是绑定?(主干)_Javascript_Backbone.js_Underscore.js - Fatal编程技术网

Javascript ';self=this';vs应用还是绑定?(主干)

Javascript ';self=this';vs应用还是绑定?(主干),javascript,backbone.js,underscore.js,Javascript,Backbone.js,Underscore.js,在我的主干代码中,我经常遇到这样的情况:我将向某个函数传递闭包,并失去“this”的上下文 一段时间以来,我的解决方案是做我看到其他人做的事情: var self = this; this.deferred.done(function () { self.render(); }); 或者实际上我切换到了\u this=this,但这不是重点。这很有效,但感觉很难看,有时我不得不经常这样做。所以我想找到一个更好的方法。我知道我可以做到这一点: this.deferred.done(fu

在我的主干代码中,我经常遇到这样的情况:我将向某个函数传递闭包,并失去“this”的上下文

一段时间以来,我的解决方案是做我看到其他人做的事情:

var self = this;

this.deferred.done(function () {
    self.render();
});
或者实际上我切换到了
\u this=this
,但这不是重点。这很有效,但感觉很难看,有时我不得不经常这样做。所以我想找到一个更好的方法。我知道我可以做到这一点:

this.deferred.done(function () {
    this.render();
}.apply(this));
我想我也可以用下划线来表示:

this.deferred.done(_.bind(function () {
    self.render();
}, this));
apply
方法看起来最简洁,但我觉得它有副作用(我只是不知道它是什么)

编辑:

看看这个JSbin,我在其中使用了类似于我提到的apply:

它可以工作,但同时会抛出一个错误。如果我将
apply
更改为
bind
,它会工作并且不会抛出错误。

  • 是一个本地方法,不需要下划线,除非您是为老式浏览器编写代码。正如@dandavis所说:
    this.deferred.done(this.render.bind(this))
    (但请注意,
    bind
    也可以绑定函数参数,而不仅仅是
    this

  • 如果您实际上是在为尖端浏览器或node.js 4编写代码,则可以使用箭头函数,该函数将
    绑定到函数定义范围内的任何内容,因此您可以编写:
    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。

      .apply()
      几乎肯定不是您想要的;我想您正在考虑
      Function.prototype.bind()
      this.deferred.done(this.render.bind(this))
      在不键入“Function”或复制的情况下工作这很有趣。未来的前景不错,但我需要比箭头功能更好的浏览器支持。Bind似乎和apply一样工作,但我现在注意到apply抛出了一个错误(我将在原来的问题中添加更多内容)。是的,因为正如Alex在回答中解释的那样,
      apply
      立即执行函数。不适用于回调。