0

Background: I am primarily a ruby/rails developer. I've been using JS/Backbone a lot recently, and I keep running in to scoping issues that I generally flail around with until it magically works.

Can someone explain/tell me of a place that explains how scoping works in JS?

Additionally, I've run in to people using 'that = this' to get around scoping issues. As I understand it, it makes the parent scope of whatever you're in 'that', so that things that are in 'that' can be accessed in deeper scopes?

I am confused.

raam86
  • 6,785
  • 2
  • 31
  • 46
Mike Manfrin
  • 2,722
  • 2
  • 26
  • 41
  • 1
    Have any sample code that is particularly confusing that we could help with? – tymeJV Oct 01 '13 at 19:42
  • 1
    Have you checked [this answer](http://stackoverflow.com/a/652387/1229023) and the link given in it? – raina77ow Oct 01 '13 at 19:42
  • See also: http://stackoverflow.com/questions/80084/in-javascript-why-is-the-this-operator-inconsistent – apsillers Oct 01 '13 at 19:47
  • Normally, functions defined inside other functions can get the outer function's variables, like `function outer() { var x = 7; function inner() { alert(x); } }`. Here, `inner` can "reach up" into `outer` and use `x`. *However*, if `inner` defined its own `x`, it couldn't use the `x` defined in `outer` because the identifier `x` wold refer to `inner`'s own `x` (we say that the inner `x` "shadows` the outer one). That's the problem with `this`: every function has its own `this`, so it shadows any outer `this` that might be available. We circumvent this by assigning the outer `this` to a new var. – apsillers Oct 01 '13 at 19:52

1 Answers1

1

In Javascript, new local scopes are only created in a function definition. But that's okay, because functions are objects and can have properties and functions of their own.

WeaponsGrade
  • 878
  • 5
  • 13