简体   繁体   English

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

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

I have a fairly simple example of a Container that stashes a value away and allows you to operate on it in isolation. 我有一个非常简单的容器示例,该容器隐藏了一个值并允许您单独对其进行操作。

For my own interest I've translated the basic structure of this object from .prototype to class syntax. 为了我自己的利益,我已将此对象的基本结构从.prototype转换为类语法。 But the example uses a funky method for creating new instances of this object and I can't figure out how to replicate it in class syntax (see code below) 但是该示例使用了一种时髦的方法来创建此对象的新实例,并且我无法弄清楚如何以类语法复制它(请参见下面的代码)

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

This translates into (class syntax): 转换为(类语法):

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

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

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

I believe that the problem is that the "of" method is simply bound to the single original instance of "Container" as a helper to make it easier to not have to write "new" every time you want to spin up an instance of this class. 我认为问题在于,“ of”方法只是绑定到“ Container”的单个原始实例作为辅助对象,从而使您每次想启动此实例时都不必编写“ new”就更容易了。类。 But I can't figure out how to replicate binding like that with the class syntax. 但是我无法弄清楚如何使用类语法复制绑定。

Is it just impossible to instantiate an own-class from one of the classe's own methods? 从类自己的方法之一实例化一个自己的类是不可能的吗?

just declare the function as static . 只需将函数声明为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