2017-07-14 246 views
1

嗨我在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但我有很多模塊,我不想管理每個特定的情況。

+0

你用'otherSet'函數試着怎麼樣? –

+0

準備好將項目遷移到使用TypeScript嗎?這將解決您只允許特定類型的對象分配的問題。 –

+0

準確地說,人們將被允許執行'complex.set('nestedProp',{x:5,y:6});''不是嗎?甚至'complex.nestedProp = {x:10,y:90}'這個還是不是? –

回答

1

看起來你認爲傳遞類似{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作爲單獨的參數(請參閱簡單的set)或作爲對象的屬性(請參閱複雜的set)。

但是,如果你認爲x和y會一直到最後,你需要在編寫代碼之前學習基本的OOP;再一次,沒有冒犯的意思。

+0

根本沒有冒犯性,但我知道Javascript是如何工作的。我只是不知道Javascript中的OOP最佳實踐,因爲你有很多自由。 Ofc我給你的例子非常簡單,但我的代碼更加複雜,我不想在每個setter中處理太多特定情況。 –

+0

那麼我很抱歉,我希望我的回答有一些幫助! – MySidesTheyAreGone

+0

^^我在開始的時候有同樣的想法,但是如果有100多個對象取決於彼此,那麼它的樣板和維護就太多了。 但是,感謝兄弟;) –