Reputation: 1352
var g = {
lang: "ttt",
l: function(){
console.log(lang);
}
}
console.log(g.l());
ReferenceError: lang is not defined
Why is lang undefined?
Upvotes: 2
Views: 689
Reputation: 5515
You need to use either g.lang
or this.lang
. this
will refer to the g
object, unless .call()
or .apply()
is used.
For example, this will result in undefined:
var g = {
lang: "ttt",
l: function(){
console.log(this.lang);
}
}
console.log(g.l.call(Math));
However, this will always give the right result (if you don't reassign g
):
var g = {
lang: "ttt",
l: function(){
console.log(g.lang);
}
}
console.log(g.l.call(Math));
Upvotes: 5
Reputation: 359776
Because this
– unlike, say, Java – is never part of the scope chain lookup. The fix:
var g = {
lang: "ttt",
l: function(){
console.log(this.lang);
}
}
console.log(g.l());
Upvotes: 3