Sarcadass Sarcadass - 5 months ago 7
Javascript Question

Can't access variable in Javascript object

I don't understand why I can't access through the b or c variables in the global function of the object object, got some trouble with variables inheritance in JS objects.

var object = {

a: 'a',

global: function() {
var b = 'b';
this.c = 'c';
},

render: function() {
console.log('render()');
return this.a + ' / ' + this.global.b + ' / ' + this.global.c;
}

};


It renders : a / undefined / undefined

I made a fiddle here

Answer

b is a variable local to the function assigned to global. It isn't a property of the object assigned to object.

c is a property that will be set on the object assigned to object after object.global() is called. It isn't a property of the function that is assigned to global.

If you want to access b and c like that then you need to either make the function an object:

global: {
    b: 'b';
    c: 'c';
},

… or make them properties of the function …

global: function () {
    // The function can do something
},

// Outside the definition of object:

object.global.b = "b";
object.global.c = "c";

… or you can have the function return them, and then access them after calling the function:

global: function () {
    return { b: "b", c: "c" };
},

// later

this.global().b;
this.global().c;