Last active
November 5, 2023 16:19
-
-
Save geerteltink/b2d7557d38700aeca10f3adae956ab04 to your computer and use it in GitHub Desktop.
Using JSON.stringify (toJSON) and JSON.parse (fromJSON) to (re)store JavaScript classes
This file contains 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
class Commit { | |
constructor(sha, payload) { | |
this.sha = sha; | |
this.repository = payload.repository; | |
this.created = new Date(); | |
} | |
toJSON() { | |
return Object.assign({}, this, { | |
created: this.created.toString() | |
}); | |
} | |
static fromJSON(json) { | |
const commit = Object.create(Commit.prototype); | |
return Object.assign(commit, json, { | |
created: new Date(json.created) | |
}); | |
} | |
} | |
let data = JSON.stringify(new Commit('b59a0b03d93f63', { | |
"repository": { | |
"owner": "xtreamwayz", | |
"name": "my-repo" | |
}, | |
})); | |
let commit = Commit.fromJSON(JSON.parse(data)); | |
console.log(data === JSON.stringify(commit), JSON.stringify(commit)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment