Created
January 2, 2011 18:26
-
-
Save nanodeath/762718 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Step 1: same as before | |
// Step 2: copy properties | |
var tmp = function(){}; | |
tmp.prototype = Person.prototype; | |
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