JavaScript “read-only” Object
This is yet the best hack I found…
function A () { // context container
var privateA = 'XYZ';
function B () {
var privateB = 'xyz';
this.v1 = 1;
this.v2 = 'b';
this.f1 = function () { return privateA; };
this.f2 = function () { return privateB; };
}
var newB = new B();
for (i in newB) arguments.callee[i] = newB[i]; // copy B methods to A
return arguments.callee;
};
A(); // initialize
A.v1; //=> 1
A.v2; //=> "b"
A.f1(); //=> "XYZ"
A.f2(); //=> "xyz"
A.v1; //=> 1
A.prototype.v1 = 2; // no effect
A.v1; //=> 1
A.v1 = 2; // A.v1 changed...
A.v1; //=> 2
A(); // regenerate...
A.v1; //=> 1 // original content
A.v3 = 'whatever';
A();
A.v3 //=> "whatever"
A.f1(); //=> "XYZ"
A.f1 = function () { return 'Oh, no! The public function is lost...' };
A.f1(); //=> "Oh, no! The public function is lost..."
A(); // come on, baby
A.f1(); //=> "XYZ" //
Have fun
Categories: Informática