JavaScript base object on another object using class and constructor

ES6 inputs class, extends, constructorand so on, which simplifies inheritance based on prototypes. I want to create an object built through a class constructor on another object. What is the cleanest way to do this in this new syntax way of constructing objects?

class A {
  constructor(json) {
     let base = JSON.parse(json);
     this.prototype = base; // ????
  }
}

I would use extends, but since the object is passed, there is no other class definition here

+4
source share
2 answers

If jsonunique to each instance, you should change this, not this.prototype. You can use Object.assignfor this:

class A {
  constructor(json) {
     let base = JSON.parse(json);
     Object.assign(this, base);
  }
}

Object.assign ( ) 1-n 0. _.assign (aka _.extend).

json , . . @Quentin Roy.

+2

json- , . @joews, , , .

, json , - :

var base = JSON.parse(json)

// Creates a Base class based on the base object.
class Base {} // or function Base(){} which is exactly the same.
Base.prototype = base;

// Extends it.
class A extends Base {
  constructor() {
  }
}

:

:

class A {
  constructor() {
  }
}
Object.assign(A.prototype, JSON.parse(json));

, base , A. :

  • base A, . ( A , super).
  • aInstance instanceof Base. .
  • , .
+1

Source: https://habr.com/ru/post/1611399/


All Articles