沙箱隔离(快照隔离)——适用于单应用

保存当前的变化,切换到另外一个的时候就恢复上一个属性

  1. // 快照方式
  2. class SnapshotSandbox {
  3. constructor() {
  4. this.proxy = window;
  5. this.modifyPropsMap = {};
  6. this.active();
  7. }
  8. active() {
  9. this.windowSnapShot = {};
  10. // 现保存一份最开始的
  11. for(const prop in window) {
  12. if (window.hasOwnProperty(prop)) {
  13. this.windowSnapShot[prop] = window[prop];
  14. }
  15. }
  16. // 将之前修改的变化赋值到当前激活状态下的值,相当于恢复上一次的修改
  17. Object.keys(this.modifyPropsMap).forEach(p => {
  18. window[p] = this.modifyPropsMap[p];
  19. })
  20. }
  21. unActive() {
  22. for(const prop in window) {
  23. if (window.hasOwnProperty(prop)) {
  24. // 判断跟一年前是不是一样,不一样就保存一下变化
  25. if (window[prop] !== this.windowSnapShot[prop]){
  26. this.modifyPropsMap[prop] = window[prop];
  27. // 恢复上一次的window,这样可以确保反复失活和激活拿到正常的状况
  28. window[prop] = this.windowSnapShot[prop];
  29. }
  30. }
  31. }
  32. }
  33. }
  34. let sandBox = new SnapshotSandbox();
  35. ((window) => {
  36. window.a = 1;
  37. window.b = 2;
  38. console.log(window.a, window.b);
  39. sandBox.unActive();
  40. console.log(window.a, window.b);
  41. sandBox.active();
  42. console.log(window.a, window.b);
  43. })(sandBox.proxy)