Skip to content Skip to sidebar Skip to footer

Can You Call Data From It's Own Json Object?

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 =

Solution 1:

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-

functionThingy(thing)
{
  this.thing = thing;
  this.things = thing + 's';
}
var obj;
obj = newThingy('thing');

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

function Thingy( thing )
{
  this.thing = thing;
}
Thingy.prototype = {
  get things() {
    returnthis.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 codethis.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:

functionThingy( thing ) {
  this.thing = thing;
}
Thingy.prototype = {
  getThings:function(){
    returnthis.thing + 's';
  }
}

Post a Comment for "Can You Call Data From It's Own Json Object?"