在JS中处理Object的嵌套属性
您好我正在编写一个模块在NodeJS中的OOP风格。
我有多个简单的对象,其中包含原始数据和多个复杂的对象包含其他对象。
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
但我有很多模块,我不想pipe理每个特定的情况。
看来你认为像{x: 1, y:2}
这样的东西传递给Complex.set会奇迹般地使x和y在Simple内部结束。 我想你对Javascript的工作方式感到困惑,没有冒犯的意思。
这里有一个实现将使事情大体上按照您所希望的方式工作。
const Simple = function Simple() { this.x = 0; this.y = 0; } Simple.prototype.getArea = function() { return this.x * this.y; } Simple.prototype.set = function (x, y) { this.x = x; this.y = y; } const Complex = function Complex() { this.nestedProp = new Simple(); } Complex.prototype.set = function(props) { this.nestedProp.set(props.x, props.y); } let complex = new Complex(); complex.nestedProp.getArea(); // 0 complex.set({x: 5, y: 6}); complex.nestedProp.getArea(); // 30
将x和y的属性显式从Complex复制到Simple,直到它们结束。 您可以将x和y作为单独的参数(请参阅Simple's set
)或作为对象的属性传递(请参阅Complex的set
)。
但是如果你认为x和y会一路走到最后,你需要在编写代码之前学习基本的OOP; 再一次,没有冒犯的意思。