Posted By

reelfernandes on 04/11/11


Tagged


Versions (?)

ECMAScript 5 Getter/Setter


 / Published in: JavaScript
 

  1. var myObject = {};
  2.  
  3. //wrapping Object.defineProperty in a function like this feels very hacky
  4. (function() {
  5. var myProp = 'myDefault';
  6. Object.defineProperty( myObject, 'myProp',
  7. {
  8. enumerable: false,
  9. configurable: true,
  10. get: function()
  11. {
  12. return myProp;
  13. },
  14. set: function( v )
  15. {
  16. myProp = v+' is mo beta';
  17. }
  18.  
  19. });
  20. })();
  21.  
  22. alert( myObject.myProp );
  23. myObject.myProp = 'myValue';
  24. alert( myObject.myProp );
  25.  
  26.  
  27. /* COULDN'T IT HAVE JUST BEEN....
  28.  
  29. Object.defineProperty( myObject, 'myProp',
  30. {
  31. writable: false,
  32. enumerable: false,
  33. configurable: true,
  34. value: 'myDefault',
  35. get: function()
  36. {
  37. return myProp;
  38. },
  39. set: function( v )
  40. {
  41. myProp = v+' is mo beta';
  42. }
  43.  
  44. });
  45. */

Report this snippet   <

Comments

RSS Icon Subscribe to comments
Posted By: reelfernandes on April 11, 2011

I meant to replace 'myProp' in the getter/setter functions with 'value';

/* COULDN'T IT HAVE JUST BEEN....

Object.defineProperty( myObject, 'myProp', 
{
    writable:       false,
    enumerable:     false,
    configurable:   true,
    value: 'myDefault',
    get: function()
    {
        return value;
        //or return this.myProp;
    },
    set: function( v )
    {
        value = v+' is mo beta';
        //or this.myProp = v+'is mo beta';
    }

});

*/

You need to login to post a comment.