I was reading Crockford’s tutorial http://javascript.crockford.com/private.html.
private variables are implemented by function inside constructor that makes possible to associate private variables to closure.
Generally javascript libraries are open, so anyone can see and modify the private variables by modifying the inner function of constructor thru instances/objects. like this:
c1.radius = function (){return 500;};
Be more precisly: In real OOPS no one can modify private variable by objects but here we can.
Can anyone please suggest me the way to make it full tamper proof like JAVA or C?
function Circle(radius) {
this.radius = function(){ return radius;}
}
Circle.prototype = {
constructor: Circle,
area: function(){
return (Math.PI)* (Math.pow(this.radius(),2));
}
};
c1 = new Circle(5);
console.log(c1.radius());
console.log(c1.area());
c1.radius = function (){return 500;};
1st off, don’t worry too much about making it tamper proof. If somebody really wants to, they’ll be able to access what they want.
2ndly, you can’t really do this unless you’re using ECMAScript 5 (IE9+, Safari 5+, Chrome 7+, FF 4+). If you’re using an ES5 browser, you can do what you want using the
Object.definePropertymethod, or usingObject.create:NOTE: When using
Object.createorObject.defineProperty, properties are by default non-writable, non-configurable (type can’t be changed and property can’t be deleted), and non-enumerable (won’t show up infor(var x in obj)constructs).