2

I have a contrived example in javascript to explain what I am trying to do:

I have an object:

var Item = {
  _first = undefined,
  _second = undefined,
  whole = putTogether()
};

function putTogether() {
  if (_first && _second) 
    return _first + '_' + _second;

  return '{ Invalid Values }';
}

I am trying to be able to access Item.whole as a property. Is there a way I can do this so that putTogether is evaluated every time it is accessed, rather than initially when the object is created?

I am aware I can define an anonymous function for Item.whole, but I am specifically trying to construct it so that it can be referenced as a value rather than a function.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
Hari Seldon
  • 1,060
  • 2
  • 13
  • 27
  • 2
    That is known as a [getter](http://stackoverflow.com/questions/812961/javascript-getters-and-setters-for-dummies). Beware of cross-browser support. – DCoder Nov 17 '12 at 17:28
  • That is the SO question I was looking for... thanks for pointing me to it! – Hari Seldon Nov 17 '12 at 17:30

2 Answers2

2

That's called a getter. Yes, it's possible:

var Item = {
  _first: undefined,
  _second: undefined
};
function putTogether() {
  if (this._first && this._second) 
    return this._first + '_' + this._second;
  return '{ Invalid Values }';
}

Object.defineProperty(Item, 'whole', {
    get: putTogether
});
Rob W
  • 341,306
  • 83
  • 791
  • 678
1

You may do this :

var Item = {
    _first : undefined,
    _second : undefined
};

Object.defineProperty(Item, "whole", {
    get : function(){
        if (this._first && this._second)  return this._first + '_' + this._second;
        return '{ Invalid Values }';
    },
});

console.log(Item.whole); // prints  { Invalid Values }
Item._first = "a";
Item._second = "b";
console.log(Item.whole); // prints a_b 

Demonstration

MDN reference of defineProperty

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Thank you for the references... How widely is the `defineProperty` method supported? – Hari Seldon Nov 17 '12 at 17:35
  • 1
    It's universally supported except on IE before 9. See [this table](http://kangax.github.com/es5-compat-table/). The support in IE8 is partial, you should test your precise case if IE8 matters for you (I have no windows box to test it). – Denys Séguret Nov 17 '12 at 17:36