Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. var C = (function () {
  2. function C() {
  3. this.v = 1;
  4. }
  5. C.prototype.f = function () {
  6. console.log('v=' + this.v);
  7. };
  8. return C;
  9. })();
  10.  
  11. var c = new C();
  12.  
  13. c.f();
  14.  
  15. var cSerializedCopy = JSON.parse(JSON.stringify(c));
  16.  
  17. cSerializedCopy.f();
  18.  
  19. v=1
  20.  
  21. .../test.js:17
  22. cSerializedCopy.f();
  23. ^
  24. TypeError: Object #<Object> has no method 'f'
  25. at Object.<anonymous> (.../test.js:17:17)
  26. at Module._compile (module.js:456:26)
  27. at Object.Module._extensions..js (module.js:474:10)
  28. at Module.load (module.js:356:32)
  29. at Function.Module._load (module.js:312:12)
  30. at Function.Module.runMain (module.js:497:10)
  31. at startup (node.js:119:16)
  32. at node.js:901:3
  33.  
  34. function wasConstructed(obj) {
  35. var c = obj.constructor;
  36. return !(c === Object || c === Array ||
  37. c === Number || c === String ||
  38. c === Boolean);
  39. }
  40.  
  41. // Returns the name of fn if fn is a function, or null otherwise
  42. function getFuncName(fn) {
  43. var funcNameRegex = /^s*functions*([^(]*)(/,
  44. results = funcNameRegex.exec(fn.toString());
  45. return (results && results.length > 1) ? results[1] : null;
  46. }
  47.  
  48. function getConstructorName(obj) {
  49. return getFuncName(obj.constructor);
  50. }
  51.  
  52. var d = new Date();
  53. var cName = getConstructorName(d); // returns "Date"
  54.  
  55. function getConstructorName(obj)
  56. {
  57. return obj.constructor.name;
  58. }
  59.  
  60. // I am going to use a Gizmo class to demonstrate my point
  61. function Gizmo(prop1, prop2, prop3) {
  62. this.prop1 = prop1;
  63. this.prop2 = prop2;
  64. this.prop3 = prop3;
  65.  
  66. // Now, this will flag what kind of object I have
  67. this.isGizmo = true;
  68. }
  69.  
  70. // Make the object
  71. var myGizmo = new Gizmo("The cat", "Thing 1", "Thing 2");
  72.  
  73. // Serialize the object
  74. var gizmoJson = JSON.stringify(myGizmo);
  75. console.log(gizmoJson);
  76.  
  77. // Now, go to rebuild the object:
  78. var rawObject = JSON.parse(gizmoJson);
  79.  
  80. // Note that rawObject needs revived.
  81. console.log("Checking if rawObject is a Gizmo: ");
  82. console.log(rawObject instanceof Gizmo);
  83.  
  84. if (rawObject.isGizmo) {
  85. var myGizmo2 = new Gizmo(rawObject.prop1, rawObject.prop2, rawObject.prop3);
  86.  
  87. console.log(myGizmo2);
  88. console.log("Checking if myGizmo2 is a Gizmo: ");
  89. console.log(myGizmo2 instanceof Gizmo);
  90. }
  91.  
  92. c instanceof C // true
  93.  
  94. cSerializedCopy instanceof C // false
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement