Skip to content

Instantly share code, notes, and snippets.

@kpozin
Forked from nanodeath/1_greet.js
Created April 7, 2011 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kpozin/908312 to your computer and use it in GitHub Desktop.
Save kpozin/908312 to your computer and use it in GitHub Desktop.
function Person(){}
Person.prototype.greet = function(){ alert("Hi!"); };
var p = new Person();
JSON.parse(JSON.stringify(p)).greet(); // throws Object #<an Object> has no method 'greet' in Chrome
var a = {"foo": "bar"};
var b = [a, a];
b[0] == b[1] // true
var c = JSON.parse(JSON.stringify(b));
c[0] == c[1] // false
// Step 1: setup
function Person(){}
Person.prototype.greet = function(){ alert("Hi!"); };
var p = new Person();
p.name = "Bob";
var object = JSON.parse(JSON.stringify(p));
try {
object.greet(); // still throws exception
} catch(e){
console.log("error calling #greet, %o", e);
}
// Step 2: change __proto__
object.__proto__ = Person.prototype;
// Step 3: verify
object.greet(); // now it works!
// Step 1: same as before
// Step 2: copy properties
var tmp = function(){};
tmp.prototype = Person.prototype;
tmp.prototype.constructor = Person;
var t = new tmp;
for (k in object) {
t[k] = object[k];
}
object = t;
// not that it matters, but object.constructor == Person now. A good thing, so you can reserialize easily.
// Step 3: verify
object.greet(); // now it works!
object instanceof Person // this is also true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment