我想创建一个工作方式类似于BigInt的类.所以我可以做:

BigInt('111') BigInt('222').toString()

请指导我如何编码.我正在使用NodeJS和普通的Java脚本.提前谢谢你了.

推荐答案

有几种解决方案.

可能最简单的方法是先创建一个普通类,然后再创建一个帮助器函数来创建对象.

class MyRealClass {
  constructor(name) {
    this.name = name;
  }
  hello() {
    console.log('Hello', this.name);
  }
}

function creteMyRealClass(name) {
  if (new.target) throw Error("Object should not be called with 'new'");
  return new MyRealClass(name);
}


creteMyRealClass('Alpha').hello();

另一种 Select 是使用调用Object.Create的帮助器函数

// By declaring an external object with attributes
// common to all objects of this type, you save memory
// and execution time
const MyPrototype = {
  hello() {
    console.log('Hello', this.name);
  },
};

function createMyPrototype(name) {
  if (new.target) throw Error("Object should not be called with 'new'");
  const obj = Object.create(MyPrototype);
  obj.name = name;
  return obj;
}

const b = createMyPrototype('Beta');
b.hello();

Javascript相关问答推荐

当promise 在拒绝处理程序被锁定之前被拒绝时,为什么我们会得到未捕获的错误?

使用JavaScript单击上一个或下一个特定按钮创建卡滑动器以滑动单个卡

react—router v6:路由没有路径

分层树视图

如何添加绘图条形图图例单击角形事件

虚拟滚动实现使向下滚动可滚动到末尾

并不是所有的iframe都被更换

我可以使用空手道用户界面来获取网页的当前滚动位置吗?

Webpack在导入前混淆文件名

使用Document.Evaluate() Select 一个包含撇号的HTML元素

如何组合Multer上传?

MongoDB中的嵌套搜索

如何在AG-Grid文本字段中创建占位符

Socket.IO在刷新页面时执行函数两次

如何在每隔2分钟刷新OKTA令牌后停止页面刷新

从异步操作返回对象

限制数组中每个元素的长度,

在使用JavaScript以HTML格式显示Google Drive中的图像时遇到问题

从客户端更新MongoDB数据库

单击子按钮时将活动切换类添加到父分区