ECMAScript 5 Getter/Setter


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  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

You need to login to post a comment.