在 javascript 中使用类构造函数创建原始类型

问题描述 投票:0回答:1

是否有可能为字符串、数字或数组等基本类型定义或扩展类?例如,我想定义一个名称类,我可以使用 new Name() 构造它,并只返回原始字符串“”

class Name extends String {}

const name = new Name()

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

背景: 我有一个键值对字典,其中值是自定义类或基元(字符串、数字)。我希望能够通过特定键从字典访问类来构造类中的对象:

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

const string = new dict["string"]()
string === "" //false
javascript class types constructor
1个回答
0
投票

这就是你所追求的吗?

下面只是从对象属性返回各个对象的新实例。当需要新类型时,函数会为它们定义构造函数。

function Point(){}
function Area(){}
function Name(){}

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

let myString = dict.string;
console.log(myString);

© www.soinside.com 2019 - 2024. All rights reserved.