skip to Main Content

Is there any possibility to define or extend a class for a primitive type like string, number or array? For example i would like to define a Name-class which I can construct with new Name() and just returns the primitive string ""

class Name extends String {}

const name = new Name()

name === "" //this is false because String-constructor does not return a primitive string

Background:
I have a dictionary of key-value pairs, where the values are either custom classes or primitives (String, Number). I want to be able to construct an object from the class by accessing the class from the dict by the specific key:

const dict = {
  "point": Point,
  "area": Area,
  "string": String,
  "name": Name,
  "number": Number,
}

const string = new dict["string"]()
string === "" //false

2

Answers


  1. Is this what you are after?

    The following just returns a new instance of the various objects from the object properties. Where new types are needed, functions define constructors for them.

    function Point(){ this.x=0; this.y=0; }
    function Area(){ this.r = 3.14; this.c = 42;}
    function Name(){}
    
    const dict = {
      point: new Point(),
      area: new Area(),
      string: new String(),
      name: new Name(),
      number: new Number(),
    }
    
    console.log(dict.point.x);
    console.log(dict.area.r);
    Login or Signup to reply.
  2. Is there any possibility to define or extend a class for a primitive type like string or number?

    No.

    or array?

    An Array is not a primitive value but an object. Yes, you can subclass Array, but it is not recommended.

    I have a dictionary of key-value pairs, where the values are either custom classes or primitives (String, Number). I want to be able to construct an object from the class by accessing the class from the dict by the specific key.

    Drop the new. Store factory functions that return the instance (or primitive value) when you call them without new:

    const dict = {
      "point": () => new Point(),
      "area"() { return new Area(); },
      "string": String,
      "name": () => { return new Name() },
      "number"() { return 0; /* Number() */ },
      // etc
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search