Javascript : class instantiation with json

javascript instantiate class
javascript object
javascript prototype
javascript model example
javascript instantiate object
javascript constructor
javascript class prototype
es6 class

I have a class "House" like :

class House{
    constructor(params){
       this.clear();
       // this = {...params} // I know that don't work !!!
       //--
       // if(params.address !== undefined) this.address = {...params.address}
       //...
    }

    clear(){
      this.address = {
         number: null,
         street: null,
         zipcode: null,
         ton: null,
      }
      this.access = {
         doorcode: null,
         stair: null,
      }
    }
}

I want to create a new instance of House and inject in constructor multiple json like :

const h = new House({address: { /* json */ }, access: { /* json */});

Or only one like :

const h = new House({access: { /* json */});

In constructor, am i obliged to check all values in "params" to insert in good properties (nested object)

I would like to avoid to create other classes like address and access and in the house constructor create new instance of each. What's the best practice ?

Regards

Using Object.assign() and object destructuring with default parameters in the constructor, you can achieve this quite easily:

class House {
  static get defaultAddress () {
    return {
      number: null,
      street: null,
      zipcode: null,
      town: null
    }
  }

  static get defaultAccess () {
    return {
      doorcode: null,
      stair: null
    }
  }

  constructor({ address = House.defaultAddress, access = House.defaultAccess } = {}) {
    this.clear()
    Object.assign(this.address, address)
    Object.assign(this.access, access)
  }

  clear () {
    const { defaultAddress, defaultAccess } = House

    Object.assign(this, { address: defaultAddress, access: defaultAccess })
  }
}

// no object
console.log(new House())
// empty object
console.log(new House({}))
// partial object
console.log(new House({ address: { number: 1, street: 'street', zipcode: 12345, town: 'town' } }))
// empty sub-objects
console.log(new House({ address: {}, access: {} }))
// partial sub-objects
console.log(new House({ address: { number: 1, street: 'street' }, access: { doorcode: 321 } }))
// complete object
console.log(new House({ address: { number: 1, street: 'street', zipcode: 12345, town: 'town' }, access: { doorcode: 321, stair: 3 } }))
.as-console-wrapper{min-height:100%!important}

Object initializer, An object initializer is an expression that describes the initialization of an notation is not the same as the JavaScript Object Notation (JSON). As another poster mentioned, the terminology between class, object and function gets a bit muddled in javascript. You can use the new keyword to instantiate a function as a "class" object. The prototype of the original function will be available to any instances in its original form and functions can use the this keyword to access a reference

You can loop through the parameters and set them manually. Then, to clear, remove all own properties (properties that aren't inherited).

class House {
  constructor(params) {
    // set data
    Object.assign(this, params);
  }

  clear() {
    for (let key in this) {
      if (this.hasOwnProperty(key))
        this[key] = undefined;  // or `delete this[key];`
    }
  }
}

let house = new House({type: "normal", height: 40});
console.log(house, house instanceof House);

Of course, you probably want to limit the input keys to a predefined set. You could store those keys in a static class variable and use them to loop through the properties in constructor and clear.

class House {
  constructor(params) {
    // check for invalid properties
    Object.keys(params).forEach(key => {
      if (!House.keys.includes(key)) 
        throw `Invalid paramater ${key}`;
    });
    // set data
    Object.assign(this, params);
  }

  clear() {
    for (let key in House.keys) {
      if (this.hasOwnProperty(key))
        this[key] = undefined;  // or `delete this[key];`
    }
  }
}
House.keys = ['type', 'height'];

let house = new House({type: 'normal', height: 40});
console.log(house, house instanceof House);

let error = new House({helloWorld: true});

Details of the object model, Define a class with a class definition; instantiate a class with constructor methods. Define and create a set of objects with constructor functions. A JavaScript class is a type of function. Classes are declared with the class keyword. We will use function expression syntax to initialize a function and class expression syntax to initialize a class. // Initializing a function with a function expression const x = function() {} // Initializing a class with a class expression const y = class {}

I think you want a common namespace for your instance properties - similar to React's props pattern - you can also specify defaults for each instance you are creating:

const defaultProps = { address: {}, access: {} };

class House {
  constructor(props = {}) {
    this.props = {...defaultProps, ...props};
  }
  clear() {
    this.props = {...defaultProps};
  }
}

JavaScript Classes: An In-Depth look (Part 1), for creating objects. Instantiation is the realization of an object from a class. Converting the array of our Objects to a Json string. Coverting a  ES6, also known as ECMAScript2015, introduced classes. A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class, and the properties are assigned inside a constructor () method. Use the keyword class to create a class, and always add the constructor () method.

JavaScript Constructors, It is considered good practice to name constructor functions with an upper-case first letter. Object Types (Blueprints) (Classes). The examples from the previous  JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.

JavaScript JSON, The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for reading and generating JSON data can be written  From our Person class, we can now create some actual people: When an object instance is created from a class, the class's constructor function is run to create it. This process of creating an object instance from a class is called instantiation — the object instance is instantiated from the class. Specialist classes

Managing complex object inputs with wrapper classes in JavaScript , The constructor of this class accepts our raw JSON input and assigns it to a “​private” (we're using vanilla JavaScript here, so no real support for  Sometimes you want to transform plain javascript object to the ES6 classes you have. For example, if you are loading a JSON from your backend, some API, or a JSON file. After you JSON.parse, it gives you a plain JavaScript object, not an instance of a class you have. For example you have a list of users that you received from the server:

Comments
  • Would Object.assign(this,params) work?
  • Good but not limited to specific keys. I'll mix with the answer below. Thank you
  • I thinks the best way to limit properties. I'll mix with previous answer. Thank you
  • How can you export all from another file ?