3

Possible Duplicate:
Self-references in object literal declarations

Within a .js file I have an object. I'd like to use some of it's data within itself. Something like...?

obj = {
    thing: 'thing',
    things: this.thing + 's'
}
Community
  • 1
  • 1
fancy
  • 48,619
  • 62
  • 153
  • 231
  • 2
    Neither JSON nor plain *JavaScript literal notation* has an internal/implicit method for handling cycles or inter-dependencies. –  Aug 31 '11 at 23:09

1 Answers1

6

You can't create an object that way, however there are a number of alternatives:

var obj;
obj = {
  thing: 'thing'
};
obj.things = obj.thing + 's';

-or-

function Thingy(thing)
{
  this.thing = thing;
  this.things = thing + 's';
}
var obj;
obj = new Thingy('thing');

or if you're using a browser that supports properties:

function Thingy( thing )
{
  this.thing = thing;
}
Thingy.prototype = {
  get things() {
    return this.thing + 's';
  },
  set things(val) {
    //there are a few things horribly wrong with this statement,
    //it's just for an example, not useful for production code
    this.thing = val[val.length - 1] == 's' ? val.substr(0, val.length - 2) : val;
  }
};

If you want to know more about them, Jon Resig has a great post about accessors and mutators, AKA getters and setters.

For cross-browser support, stick with a function call for the plural form and only provide an accessor:

function Thingy( thing ) {
  this.thing = thing;
}
Thingy.prototype = {
  getThings:function(){
    return this.thing + 's';
  }
}
zzzzBov
  • 174,988
  • 54
  • 320
  • 367