Travis Pettry
Travis Pettry

Reputation: 1352

Accessing variable defined above in object literal causes ReferenceError

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

Answers (2)

phenomnomnominal
phenomnomnominal

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

Matt Ball
Matt Ball

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

Related Questions