If you want to preserve the inheritance hierarchy by specifying all the properties before creating the object, you can follow the approach below. This approach prints a chain of prototype hierarchies.
Note. In this approach, you do not need to create a constructor first.
function myself() { this.g = ""; this.h = []; this.i = {}; myself.prototype = new parent(); myself.prototype.constructor = myself; } function parent() { this.d = ""; this.e = []; this.f = {}; parent.prototype = new grandParent(); parent.prototype.constructor = parent; } function grandParent() { this.a = ""; this.b = []; this.c = {}; } var data = new myself(); var jsonData = {}; do { for(var key in data) { if(data.hasOwnProperty(key) && data.propertyIsEnumerable(key)) { jsonData[key] = data[key]; } } data = Object.getPrototypeOf(data).constructor.prototype; Object.defineProperties(data, { 'constructor': { enumerable: false } }); } while (data.constructor.name !== "grandParent") console.log(jsonData);
source share