Messing Around in JS Object - Prevent Extensions October 25, 2011
Lately I've been messing around with Javascript Object in Javascript 1.8.5 or greater. It's interesting but I've come across some peculiarities.
Object.preventExtensions tests
function d(){
this._test = 5;
}
//Object.preventExtensions(d.prototype);
if (Object.isExtensible(d.prototype)){
Object.defineProperty(d.prototype, "test",
{
get:
function(){ console.log("get called"); return this._test; },
enumerable: false,
configurable: true
}
);
}
var s = new d();
Object.preventExtensions(s);
s.test = 6;
console.log(s.test);
s.jason = "jason";
console.log(s.jason);
Calling preventExtensions on d.prototype, the "test" property is never defined with the getter, so console.log(s.test) won't also log "get called". Object.preventExtensions(d.prototype) does not prevent extensions on instances of d. This one was weird to me, but they are two separate objects, so creating the property "jason" on "s" works unless I prevent extensions on "s". When preventExtensions is called on "s", console.log(s.test) prints 5 and console.log(s.jason) does not error out although it raises an error if I try to extend the prototype when it is not extensible.
Just some observations... This is the first in a series of posts on Object and its new methods in 1.8.5, I feel I need to know everything about it