Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var C = (function () {
- function C() {
- this.v = 1;
- }
- C.prototype.f = function () {
- console.log('v=' + this.v);
- };
- return C;
- })();
- var c = new C();
- c.f();
- var cSerializedCopy = JSON.parse(JSON.stringify(c));
- cSerializedCopy.f();
- v=1
- .../test.js:17
- cSerializedCopy.f();
- ^
- TypeError: Object #<Object> has no method 'f'
- at Object.<anonymous> (.../test.js:17:17)
- at Module._compile (module.js:456:26)
- at Object.Module._extensions..js (module.js:474:10)
- at Module.load (module.js:356:32)
- at Function.Module._load (module.js:312:12)
- at Function.Module.runMain (module.js:497:10)
- at startup (node.js:119:16)
- at node.js:901:3
- function wasConstructed(obj) {
- var c = obj.constructor;
- return !(c === Object || c === Array ||
- c === Number || c === String ||
- c === Boolean);
- }
- // Returns the name of fn if fn is a function, or null otherwise
- function getFuncName(fn) {
- var funcNameRegex = /^s*functions*([^(]*)(/,
- results = funcNameRegex.exec(fn.toString());
- return (results && results.length > 1) ? results[1] : null;
- }
- function getConstructorName(obj) {
- return getFuncName(obj.constructor);
- }
- var d = new Date();
- var cName = getConstructorName(d); // returns "Date"
- function getConstructorName(obj)
- {
- return obj.constructor.name;
- }
- // I am going to use a Gizmo class to demonstrate my point
- function Gizmo(prop1, prop2, prop3) {
- this.prop1 = prop1;
- this.prop2 = prop2;
- this.prop3 = prop3;
- // Now, this will flag what kind of object I have
- this.isGizmo = true;
- }
- // Make the object
- var myGizmo = new Gizmo("The cat", "Thing 1", "Thing 2");
- // Serialize the object
- var gizmoJson = JSON.stringify(myGizmo);
- console.log(gizmoJson);
- // Now, go to rebuild the object:
- var rawObject = JSON.parse(gizmoJson);
- // Note that rawObject needs revived.
- console.log("Checking if rawObject is a Gizmo: ");
- console.log(rawObject instanceof Gizmo);
- if (rawObject.isGizmo) {
- var myGizmo2 = new Gizmo(rawObject.prop1, rawObject.prop2, rawObject.prop3);
- console.log(myGizmo2);
- console.log("Checking if myGizmo2 is a Gizmo: ");
- console.log(myGizmo2 instanceof Gizmo);
- }
- c instanceof C // true
- cSerializedCopy instanceof C // false
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement