-2
1. var a = {
             arr:[], 
             method:function method(){
                     console.log(this.arr)} //this is undefined
             }
2. var a = arr:[], 
             method:function(){
                     console.log(this.arr)} //this gives a
             }

Can somebody explain me why this context gets lost in the first example?

Volker E.
  • 5,443
  • 11
  • 43
  • 62
  • 2
    Nope it isnt. The only difference is that you can call *method* inside the first *method* ... – Jonas Wilms Jul 22 '17 at 11:08
  • There's no contexts in you example at all. Please show a use case which reproduces your issue. – Teemu Jul 22 '17 at 11:08
  • 2
    What makes you think the `this` context gets lost? For more details, google for "JavaScript named function expression". –  Jul 22 '17 at 11:08
  • @Jonasw In that case the context will be lost, if calling directly `method()` within `a.method`. – Teemu Jul 22 '17 at 11:10

1 Answers1

0

The first one is a named function expression the second is anonymous. The first one will be better for stack trace.

Win
  • 4,602
  • 2
  • 10
  • 15