4

How would I go about referencing a JavaScript hash key within the object itself? Fore example, I want to be able to actually make use of the "theme" key. Would I use "this" to reference "theme"?

window.EXAMPLE = {
config : {
    theme: 'example',
    image_path: '/wp-content/themes/' + this.theme + '/img/',
}
}
Matt
  • 2,317
  • 7
  • 41
  • 52

4 Answers4

7

You could use a method:

window.EXAMPLE = {
    config : {
        theme: 'example',
        image_path: function () {
            return '/wp-content/themes/' + this.theme + '/img/';
        },
    }
}

Of course, then you have to access it via EXAMPLE.config.image_path()

You should probably not be defining things on window either, and just use whatever the current scope is.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
3

The only way to do that is with a function:

e.g.

windows.EXAMPLE {
  config : {
    theme: 'blah', 
    image_path: function () { return '/path/to' + this.theme } 
  } 
} 
Rob Stevenson-Leggett
  • 35,279
  • 21
  • 87
  • 141
2

Without using a function, you have to split it into two separate assignments:

window.EXAMPLE = {
    config : {
        theme: 'example'
    }
};
window.EXAMPLE.config.image_path = '/wp-content/themes/' + window.EXAMPLE.config.theme + '/img/';
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
1

When constructing an object (not once it is created, as Kyle's example gives), I don't think it's possible to access the object's properties, as it does not "exist" yet, unless you use functions or some fancy stuff.

I also see no reason to do this, either, as you could either just type "example" in the image_path value anyway, or you could create a variable before the definition to act as a "configuration" constant:

var CONF_THEME = 'example';
window.EXAMPLE = {
    config : {
        theme: CONF_THEME,
        image_path: '/wp-content/themes/' + CONF_THEME + '/img/'
    }
}
Ross Brunton
  • 173
  • 5