【问题标题】:var that = this in javascript [duplicate]var that = this in javascript [重复]
【发布时间】:2017-09-18 12:23:15
【问题描述】:

有时,我会遇到这样一段 javascript 代码:

function someFunc() {
    var that = this;
    // do something with that
}

当您可以使用“this”时,为什么人们会这样做?

【问题讨论】:

  • 因为this 并不总是你expect it to be
  • 以防 this 稍后重新定义。通过将原始引用存储在变量中,即使在其他内部范围内,您仍然可以访问原始范围的 ```this``
  • 这个问题的答案可能就像雅培和科斯特洛的例行公事。
  • @dan1111 不,that 问题,不是这个。

标签: javascript this


【解决方案1】:

检查这个例子:

function someFunc() {
  var that = this;
  $('.test').on('click', function() {
    //in this scope the this will be different and if you'd like to use the this of someFunc then you need to assign another variable
  })
}

【讨论】:

    猜你喜欢
    • 2012-09-04
    • 2011-07-18
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    相关资源
    最近更新 更多