Last active
February 22, 2018 16:19
-
-
Save akccakcctw/492e5ee84bad803c5c36d5197497d407 to your computer and use it in GitHub Desktop.
深拷貝的幾種方法
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
// ref: https://mobile.twitter.com/DasSurma/status/955484341358022657 | |
// https://dassur.ma/things/deep-copy/ | |
// performance: https://deep-copy.glitch.me/ | |
// JSON | |
function structuredCloneJSON(obj) { | |
return JSON.parse(JSON.stringify(obj)); | |
} | |
// History API | |
function structuredCloneHistory(obj) { | |
const oldState = history.state; | |
history.replaceState(obj, window.title); | |
const copy = history.state; | |
history.replaceState(oldState, window.title); | |
return copy; | |
} | |
// MessageChannel | |
function structuredCloneMessage(obj) { | |
return new Promise(resolve => { | |
const {port1, port2} = new MessageChannel(); | |
port2.onMessage = ev => resolve(ev.data); | |
port1.postMessage(obj); | |
}); | |
} | |
// Notification API | |
function structuredCloneNotification(obj) { | |
return new Notification('', {data: obj, silent: true}).data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment