Reputation: 147
var a = {
text : 3,
logText : function () {
console.log(this.text);
},
callLogText : function() {
logText();
}
};
a.callLogText();
This will genernate a ReferenceError: logText is not defined
error message.
Instead, you prefix this
to the logText()
method, it will be ok. No error msg will pop.
var a = {
text : 3,
logText : function () {
console.log(this.text);
},
callLogText : function() {
this.logText();
}
};
I really cant figure out the reason.
Upvotes: 2
Views: 360
Reputation: 328556
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.
Upvotes: 4
Reputation: 5492
Calling
logText();
means somewhere there is a function named logText(), but here you have defined logText() as a property of an object, so to access the logText() you have to refer it with the help of the object it is defined in. In this case it is in the same object so you refer to the same object by saying this.
Upvotes: 0
Reputation: 160833
logText();
is to execute a global function logText
which is undefined.
this.logText();
is to execute the function a.logText
.
Upvotes: 0
Reputation: 28711
It's not a quirk. It's how most languages function when it comes to objects.
logText()
is a method of the a
object, not a function.
You need to call methods internally as this.methodName()
or externally as object.methodName()
.
Upvotes: 0