Advertisement
AyrA

Real private setter in ES5

Sep 10th, 2017
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //object with a private setter in JavaScript
  2. //lulz.A can only be set via a special function and the value needs to be a number
  3. function lulz(){
  4.     var a=0;
  5.     Object.defineProperty(this, 'A',{
  6.         get:function(){return +a;},
  7.         enumerable:true,
  8.         configurable:false
  9.     });
  10.     this.setA=function(q){
  11.         //only allow numbers
  12.         if(+q==+q){return a=+q;}
  13.     };
  14.     return this;
  15. }
  16.  
  17. var test=new lulz();
  18. //Check initial
  19. console.log("A must be 0 as initial value:",test.A===0);
  20. //Try direct modify
  21. test.A=12;
  22. console.log("A must be 0 after assigning 12 directly:",test.A===0);
  23. //Try direct modify
  24. test.A="Q";
  25. console.log("A must be 0 after assigning 'Q' directly:",test.A===0);
  26. //Try indirect modify with string
  27. test.setA("Q");
  28. console.log("A must be 0 after assigning 'Q' via set function:",test.A===0);
  29. //Try indirect modify with number
  30. test.setA(12);
  31. console.log("A must be 12 after assigning 12 via set function:",test.A===12);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement