You need to learn the JavaScript scoping rules. This blog post gives a good introduction.
In a nutshell, JavaScript follows some rules when you use a variable name (for the purpose of this explanations, function definitions are pretty much like variable declarations).
What probably confuses you is this:
var a = { b: ...};
var a = function() { var b = ... }
In both cases, you get a new variable a
. In the first case, it's an object with a property b
. In the second case, it's a function which has a nested scope in which a new variable b
is defined.
JavaScript will look in the current and all parent scopes for variables. But object definitions are no scopes. As far as JavaScript is concerned, the property b
is invisible unless you make it visible by using the special variable this
which always references the "current" object (in your example, that is a
).
Since the properties of the object a
are not "in scope", JavaScript can't find logText()
unless you tell it to look in this
. If you don't say anything, JavaScript will look in the current scope (the body of the function callLogText
), then the parent scope (in which a
is defined) and then in any parent scopes of that.