AyrA icon

Real private setter in ES5

AyrA | PRO | 09/11/17 02:35:40 AM UTC | 0 ⭐ | 500 👁️ | Never ⏰ | []
JavaScript |

920 B

|

None

|

0 👍

/

0 👎

//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);

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎