Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //object with a private setter in JavaScript
- //lulz.A can only be set via a special function and the value needs to be a number
- function lulz(){
- var a=0;
- Object.defineProperty(this, 'A',{
- get:function(){return +a;},
- enumerable:true,
- configurable:false
- });
- this.setA=function(q){
- //only allow numbers
- if(+q==+q){return a=+q;}
- };
- return this;
- }
- var test=new lulz();
- //Check initial
- console.log("A must be 0 as initial value:",test.A===0);
- //Try direct modify
- test.A=12;
- console.log("A must be 0 after assigning 12 directly:",test.A===0);
- //Try direct modify
- test.A="Q";
- console.log("A must be 0 after assigning 'Q' directly:",test.A===0);
- //Try indirect modify with string
- test.setA("Q");
- console.log("A must be 0 after assigning 'Q' via set function:",test.A===0);
- //Try indirect modify with number
- test.setA(12);
- 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