ECMAScript 5 Getter/Setter Alt


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



Copy this code and paste it in your HTML
  1. var myObject = {};
  2.  
  3. Object.defineProperty( myObject, '_myProp',
  4. {
  5. value: 'myDefault',
  6. writable: false,
  7. enumberable: false,
  8. configurable: true
  9. });
  10.  
  11. Object.defineProperty( myObject, 'myProp',
  12. {
  13. enumberable: true,
  14. configurable: true,
  15. set: function( v )
  16. {
  17. Object.defineProperty( this, '_myProp', { writable:true } );
  18. this._myProp = v;
  19. Object.defineProperty( this, '_myProp', { writable:false } );
  20. },
  21. get: function()
  22. {
  23. return this._myProp;
  24. }
  25.  
  26. });
  27.  
  28. alert( myObject.myProp );
  29. myObject.myProp = 'myValue';
  30. alert( myObject.myProp );
  31. myObject._myProp = 'teehee, not writable';
  32. alert( myObject._myProp );

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.