繁体   English   中英

如何使用类语法复制Javascript构造函数和原型对象

[英]How to replicate Javascript Constructor & Prototype objects with Class Syntax

我有一个非常简单的容器示例,该容器隐藏了一个值并允许您单独对其进行操作。

为了我自己的利益,我已将此对象的基本结构从.prototype转换为类语法。 但是该示例使用了一种时髦的方法来创建此对象的新实例,并且我无法弄清楚如何以类语法复制它(请参见下面的代码)

const Container = function(x) {
  this.val = x
}

Container.prototype.map = function(f) {
  return Container.of(f(this.val))
}

Container.of = function(x) { return new Container(x) } // Problem spot

转换为(类语法):

class Container {
  constructor(x) {
    this.val = x
  }

  map(f) {
    return Container.of(f(this.val))
  }

  of = (x) => {                       // ????????
    return new Container(x)
  }
}

我认为问题在于,“ of”方法只是绑定到“ Container”的单个原始实例作为辅助对象,从而使您每次想启动此实例时都不必编写“ new”就更容易了。类。 但是我无法弄清楚如何使用类语法复制绑定。

从类自己的方法之一实例化一个自己的类是不可能的吗?

只需将函数声明为static

class Container {
  constructor(x) {
    this.val = x
  }

  map(f) {
    return Container.of(f(this.val))
  }

  static of(x) {                       // ????????
    return new Container(x)
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM