Skip to content

Instantly share code, notes, and snippets.

@zpao
Created May 27, 2012 00:11
Show Gist options
  • Save zpao/2795701 to your computer and use it in GitHub Desktop.
Save zpao/2795701 to your computer and use it in GitHub Desktop.
Exploring prototypes & Object.freeze
function makeObj(freeze) {
var o = {
foo: "bar",
doit: function() {
console.log(this.foo);
}
}
if (freeze)
Object.freeze(o);
return o;
}
// A: unfrozen object used as prototype;
try {
console.log("A");
var obj = makeObj(false);
function A() {};
A.prototype = obj;
A.prototype.foo = "qux";
A.prototype.something = function() {
console.log("wat");
}
var a = new A();
obj.doit();
a.doit();
a.something();
}
catch (e) {
console.error(e)
}
// B: frozen object used as prototype
try {
console.log("B");
var obj = makeObj(true);
function B() {};
B.prototype = obj;
B.prototype.foo = "qux";
B.prototype.something = function() {
console.log("wat");
}
var b = new B();
obj.doit();
b.doit();
b.something();
}
catch (e) {
console.error(e);
}
// C: frozen object with properties copied to prototype
try {
console.log("C");
var obj = makeObj(true);
function C() {};
for (key in obj) {
C.prototype[key] = obj[key];
}
C.prototype.foo = "qux";
C.prototype.something = function() {
console.log("wat");
}
var c = new C();
obj.doit();
c.doit();
c.something();
}
catch (e) {
console.error(e);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment