Simon Bruneaud
Simon Bruneaud

Reputation: 2557

Handle nested properties of Object in JS

Hi I'm writing a module in NodeJS in a OOP style.

I have multiples simples objects that contains primitive data and multiple complex objects that contain other objects.

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);
}

My problem is that users who will use my API can break things by doing this:

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  <----

Is there a lodash function to only assign values of such nested Object.
Or is there a good way to manage this kind of problems?

Note: I could check for instanceof but I have a lot of modules, and I don't want to manage each specific case.

Upvotes: 1

Views: 106

Answers (1)

MySidesTheyAreGone
MySidesTheyAreGone

Reputation: 129

It seems you think passing something like {x: 1, y:2} to Complex.set will magically make x and y end inside of Simple. I think you are confused about how Javascript works, no offense meant.

Here's an implementation that would make things work roughly the way you seem to want.

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

The properties x and y are passed explicitly from Complex to Simple until they end where they should. You can either pass x and y as separate parameters (see Simple's set) or as properties of an object (see Complex's set).

But if you thought x and y would make it all the way to the end by themselves you need to study basic OOP before writing code; again, no offense meant.

Upvotes: 1

Related Questions