嗨我在OOP风格的NodeJS中编写模块。在JS中处理对象的嵌套属性
我有多个包含原始数据的简单对象和包含其他对象的多个复杂对象。
const Simple = function Simple() {
this.x = 0;
this.y = 0;
}
Simple.prototype.getArea = function() {
return this.x * this.y;
}
const Complex = function Complex() {
this.ownProp = 0;
this.nestedProp = new Simple();
this.otherNestedProp = new otherSimple();
}
Complex.prototype.set = function(key, value) {
this[key] = value;
}
Complex.prototype.otherSet = function(value) {
Object.assign(this, value);
}
我的问题是,谁将会使用我的API可以通过这样做打破东西的用户:
let simple = new Simple();
simple.getArea(); // 0
let complex = new Complex();
complex.nestedProp.getArea(); // 0
complex.set('nestedProp', {x: 5, y: 6});
complex.nestedProp.getArea(); // THROW <----
let complex = new Complex();
complex.nestedProp.getArea(); // 0
complex.set({nestedProp: {x: 5, y: 6});
complex.nestedProp.getArea(); // THROW <----
是否有lodash功能只分配这样的嵌套对象的值。
还是有一个很好的方法来管理这类问题?
注:我可以检查instanceof
但我有很多模块,我不想管理每个特定的情况。
你用'otherSet'函数试着怎么样? –
准备好将项目迁移到使用TypeScript吗?这将解决您只允许特定类型的对象分配的问题。 –
准确地说,人们将被允许执行'complex.set('nestedProp',{x:5,y:6});''不是吗?甚至'complex.nestedProp = {x:10,y:90}'这个还是不是? –