Javascript-将父级和子级的属性打包在同一JSON字符串中
我有一个javascript场景,其中我创建了一个基类和一个派生类,并希望使用JSON.stringify()将整个属性集打包成一个JSON字符串 当我使用与下面代码等效的代码时,我仅在对一个DerivedClass实例运行“toString()”时获取子对象的属性:Javascript-将父级和子级的属性打包在同一JSON字符串中,javascript,class,inheritance,Javascript,Class,Inheritance,我有一个javascript场景,其中我创建了一个基类和一个派生类,并希望使用JSON.stringify()将整个属性集打包成一个JSON字符串 当我使用与下面代码等效的代码时,我仅在对一个DerivedClass实例运行“toString()”时获取子对象的属性: function BaseClass() { this.version = "0.0.0"; this.time = Date.now(); this.type = this.constructor.nam
function BaseClass() {
this.version = "0.0.0";
this.time = Date.now();
this.type = this.constructor.name;
}
BaseClass.prototype.BaseClassException = function(message) {
this.message = message;
}
BaseClass.prototype.toString = function() {
return JSON.stringify(this);
}
BaseClass.parse = function(jsonString) {
var json = JSON.parse(jsonString);
switch(json.type) {
case "DerivedClass1":
return new DerivedClass1();
case "DerivedClass2":
return new DerivedClass2();
default:
throw new BaseClassException("No compatible type found when parsing: " + jsonString);
}
function DerivedClass1(prop1, prop2) {
this.prop1 = prop1;
this.prop2 = prop2;
this.type = this.constructor.name;
}
DerivedClass1.prototype = new BaseClass();
DerivedClass1.prototype.constructor = DerivedClass1;
function DerivedClass2(prop3) {
this.prop3 = prop3;
}
DerivedClass2.prototype = new BaseClass();
DerivedClass2.prototype.constructor = DerivedClass2;
// Test
var dc1 = new DerivedClass1("A", "B");
console.log(dc1.toString()); // Returns JSON-string with properties of DerivedClass1, but not BaseClass
将有几个不同的派生类。虽然我知道js并不真正支持类,但我仍然希望将来自基对象和子对象的所有属性打包在同一个JSON字符串中。该结构是与整个系统的其他节点关联所必需的,即所有属性都需要存在
如果同时有人能告诉我正确的方向来理解子对象和父对象之间的联系,以便我更好地理解js的“继承”部分,我也会非常感激。我更习惯于严格的oo语言,所以我很乐意学习。有两件事我可以很容易地提出建议
function DerivedClass1(prop1, prop2) {
BaseClass.call(this);
this.prop1 = prop1;
this.prop2 = prop2;
this.type = this.constructor.name;
}
我们使用当前对象调用父构造函数。这里需要注意的重要一点是,我们正在将当前上下文设置为类型为DerivedClass1
的对象DerivedClass1.prototype = Object.create(BaseClass.prototype);
在您的例子中,基类的构造函数不依赖于任何参数。因此,执行DerivedClass1.prototype=new BaseClass()代码>不会有很大的区别。但最好只依赖父构造函数的原型。阅读有关使用对象的更多信息。在此中,为继承创建
注意,您可以从Java来考虑这一点,在JavaScript中,
super
调用是显式的。在Java中,调用super
在派生类中是可选的,而在JavaScript中,如果希望使用基类构造函数显式构造,则必须调用BaseClass.call(this)
。虽然这是不准确的,但它应该会给你很好的直觉在OP的例子中,代码>对于继承来说是非常好的,但是我同意Object.create在这里更好。@BenjaminGruenbaum+thefourtheye你们和这个社区能够提供的快速和高质量的答案真是太棒了。谢谢你分享你的知识!我希望它对其他许多人也有用。:)JavaScript的特点是原型继承,它是关于共享功能而不是结构的。看,在我的回答中,我认为你的情况是正确的。@BenjaminGruenbaum谢谢你,我会读的!