Skip to content

Instantly share code, notes, and snippets.

@akccakcctw
Last active February 22, 2018 16:19
Show Gist options
  • Save akccakcctw/492e5ee84bad803c5c36d5197497d407 to your computer and use it in GitHub Desktop.
Save akccakcctw/492e5ee84bad803c5c36d5197497d407 to your computer and use it in GitHub Desktop.
深拷貝的幾種方法
// 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