Sarcadass Sarcadass - 4 months ago 4x
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() {
return this.a + ' / ' + + ' / ' +;


It renders : a / undefined / undefined

I made a fiddle here


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 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: = "b"; = "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;;