Advertisement
Guest User

Untitled

a guest
Feb 26th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width">
  6. <title>JS Bin</title>
  7. </head>
  8. <body>
  9.  
  10. <script id="jsbin-javascript">
  11. function Observer(data) {
  12. this.data = data;
  13. this.traversal(data);
  14. }
  15.  
  16. Observer.prototype.traversal = function(obj) {
  17. let val;
  18. for (let key in obj) {
  19. if (obj.hasOwnProperty(key)) {
  20. val = obj[key];
  21.  
  22. if (typeof val === 'object') {
  23. new Observer(val);
  24. }
  25. this.convert(key, val);
  26. }
  27. }
  28. }
  29.  
  30. Observer.prototype.convert = function(key, val) {
  31. Object.defineProperty(this.data, key, {
  32. configurable: true,
  33. enumerable: true,
  34. get: function() {
  35. console.log(`你访问了 ${key}`);
  36. return val;
  37. },
  38. set: function(newVal) {
  39. console.log(`你设置了 ${key}, 新的值为${newVal}`);
  40. if (val === newVal) return;
  41. val = newVal;
  42. }
  43. });
  44. }
  45.  
  46. let app1 = new Observer({
  47. name: 'youngwind',
  48. age: 25
  49. });
  50.  
  51. let app2 = new Observer({
  52. university: 'bupt',
  53. major: 'computer'
  54. });
  55.  
  56. app1.data.name;
  57. app1.data.age = 100;
  58. app2.data.university;
  59. app2.data.major = 'science';
  60. </script>
  61.  
  62.  
  63.  
  64. <script id="jsbin-source-javascript" type="text/javascript">function Observer(data) {
  65. this.data = data;
  66. this.traversal(data);
  67. }
  68.  
  69. Observer.prototype.traversal = function(obj) {
  70. let val;
  71. for (let key in obj) {
  72. if (obj.hasOwnProperty(key)) {
  73. val = obj[key];
  74.  
  75. if (typeof val === 'object') {
  76. new Observer(val);
  77. }
  78. this.convert(key, val);
  79. }
  80. }
  81. }
  82.  
  83. Observer.prototype.convert = function(key, val) {
  84. Object.defineProperty(this.data, key, {
  85. configurable: true,
  86. enumerable: true,
  87. get: function() {
  88. console.log(`你访问了 ${key}`);
  89. return val;
  90. },
  91. set: function(newVal) {
  92. console.log(`你设置了 ${key}, 新的值为${newVal}`);
  93. if (val === newVal) return;
  94. val = newVal;
  95. }
  96. });
  97. }
  98.  
  99. let app1 = new Observer({
  100. name: 'youngwind',
  101. age: 25
  102. });
  103.  
  104. let app2 = new Observer({
  105. university: 'bupt',
  106. major: 'computer'
  107. });
  108.  
  109. app1.data.name;
  110. app1.data.age = 100;
  111. app2.data.university;
  112. app2.data.major = 'science';</script></body>
  113. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement