0

This is a contrived example but I'm just trying to understand how scoping works. Can someone explain why the following throws an error? I'm not sure why adding this.otherThing = otherThing would be necessary if callback is executed in the context of where otherThing is defined.

function doSomething(callback){
// works if the following is added
// this.otherThing = otherThing

  function otherThing(val){
    return val
  }

  callback()
}


let callback = someVal => {
    console.log('was given:',otherThing(someVal))
}

doSomething(() => callback('some value'))

jsbin link

user2535381
  • 588
  • 1
  • 7
  • 10
  • Move the function "otherThing" outside. Why do you need it inside of "doSomething"? – anomaaly Oct 30 '17 at 23:20
  • 1
    `this.otherThing` makes it defined to the global scope. Otherwise it is just defined locally, meaning it can't be called outside the `doSomething` function – Patrick Evans Oct 30 '17 at 23:20
  • 1
    JavaScript has **lexical** scope. A function cannot access something that is not defined in its scope or that is not accessible in the scope it is defined in. – Felix Kling Oct 30 '17 at 23:26
  • 1
    *"works if the following is added `this.otherThing = otherThing`"* That's a misleading behavior. Assigning to `this.otherThing` will create a global variable because `this` refers to the global object. If your functions were *strict*, assigning to `this.otherThing` would not work. – Felix Kling Oct 30 '17 at 23:28
  • @Felixl Ok. So the otherThing call inside the callback declaration will be trying to look for otherThing inside where it was declared (in this case the function callback) instead of where it was called. And the reason this.otherThing worked is because before I called the callback function I set a variable on window to be equal to the function in that closure. Does that sound right? – user2535381 Oct 30 '17 at 23:38
  • Yes, that sounds about right. – Felix Kling Oct 31 '17 at 16:52

0 Answers0