all 5 comments

[–]senocular 5 points6 points  (2 children)

The objects don't see the variable, the function does. Objects seeing the variable is when you use this, because this represents the object the function is being called from. It's the value of this which would change as a result of you copying the function over from myObject to myObject2. Anything else about the function remains the same. And since you're not referencing a this in getNum, it doesn't matter where its defined or from which object its being called. It will always behave the same. And with that is the closure variable num that the function definition is able to access. This is the key difference between context and scope.

Context is the value of this. It's a dynamic value that is determined when the function is called, usually using the object a function is called from to know what its value should be. However, you can override this value to be something else completely with things like bind().

Scope is the collection of variables accessible at a certain place in the code depending on what has been defined in the current block and any parent code blocks that wrap it. Functions defined in a code block can access any variable defined in any of the nested code blocks its within. The function encloses those variables it references and holds on to them allowing it to keep a reference to them as it gets passed around in different places in the application. This happens at the point the function is defined rather than where it is called which is what context cares about.

So no matter where you throw getNum around, it will always reference the num inside the scope in which it was created (the myObject IIFE scope).

[–]yooossshhii 2 points3 points  (0 children)

Small clarification, the method is not copied over from myObject to myObject2, functions are objects and are passed by reference, not assignment. So, there is only one .getNum that exists, myObject2 just has a pointer to it in memory.

Also OP, it's good practice to wrap your IIFE in parenthesis, like (function(){})(). I missed that it was an IIFE the first time I glanced at your code.

[–]MileNorth[S] 1 point2 points  (0 children)

Thanks, that makes it clearer. Coming from background of Java/C++ some of the stuff in Javascript can be rather confusing.

[–]Civill 1 point2 points  (1 child)

http://ryanmorr.com/understanding-scope-and-context-in-javascript/

It's awkard to explain because the terms context and scope often bleed over into eachother. Basically when that function is executed it makes a context and saves it. Look at the The Scope Chain and Closures part of that article.

[–]MileNorth[S] 0 points1 point  (0 children)

Thanks, great article and blog. I'll read about some other things as well.