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.
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:
In both cases, you get a new variable
a. In the first case, it’s an object with a propertyb. In the second case, it’s a function which has a nested scope in which a new variablebis 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
bis invisible unless you make it visible by using the special variablethiswhich always references the “current” object (in your example, that isa).Since the properties of the object
aare not “in scope”, JavaScript can’t findlogText()unless you tell it to look inthis. If you don’t say anything, JavaScript will look in the current scope (the body of the functioncallLogText), then the parent scope (in whichais defined) and then in any parent scopes of that.