0

Sometimes, I come across a piece of javascript code like this:

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

Why do people do this when you can just use 'this'?

user3685285
  • 4,678
  • 8
  • 35
  • 80
  • 2
    Becuase `this` isn't always what you [expect it to be](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Matt Burland Apr 21 '17 at 13:17
  • 1
    In case ```this``` gets redefined later. By storing the original reference in a variable you still have access to the original scope's ```this``, even within other inner scopes – Luke K Apr 21 '17 at 13:17
  • 1
    Maybe this helps: http://stackoverflow.com/questions/4371333/is-var-self-this-a-bad-pattern – kalsowerus Apr 21 '17 at 13:17
  • 1
    The answer to this question could be like an Abbott and Costello routine. –  Apr 21 '17 at 13:18
  • `function someFunc() { var that = this; var someOther = function(){ that.theyCame(); // ? }; }` – Suresh Atta Apr 21 '17 at 13:19
  • 1
    @dan1111 No, `that` question, not this. – deceze Apr 21 '17 at 13:19

1 Answers1

1

Check this example:

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
  })
}
Peter Kota
  • 6,370
  • 4
  • 21
  • 46