javascript - 使用 es6 类进行自调用类实例化

标签 javascript function class

我正在尝试使用 Simple “Class” Instantiation其中一个类可以返回 new自身的版本并返回自身的实例化版本。

function User(first, last){
  if ( this instanceof User ) {
    this.name = first + " " + last;
  } else
    return new User(first, last);
}

我正在尝试使用 es6 类查看这是否可行。
class User {
  constructor(first, last){
    if ( this instanceof User ) {
      this.name = first + " " + last;
    } else
      return new User(first, last);
    }
  }  
}

但是我遇到了这个错误:

TypeError: Class constructor User cannot be invoked without 'new'



我想知道是否有办法解决它。

最佳答案

I'm wondering if there's a way around it.



嗯,不。我认为这是一件好事。与之前的方法相比,使用 ES6 Class 的优势在于它实际上表现得像一个类,没有怪癖和困惑。如果您采取理由去做您想做的事情,请从您引用的文章中:

First is an issue that new JavaScript programmers will encounter. On a quick observation of the above code it isn’t immediately obvious that the function is actually something that is meant to be instantiated...

Secondly, if a Class-style function is meant to be instantiated, and isn’t, it can in turn end up polluting the current scope...



这些是 ES6 旨在解决的一些问题。所以,现在,新的程序员进来了,尝试以错误的方式调用一个类,然后繁荣:TypeError。没有污染的范围,没有意外的行为。

关于javascript - 使用 es6 类进行自调用类实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48877083/

相关文章:

javascript - 使用 cors 从 aws s3 加载的 Canvas 元素和图像在第一次加载时不起作用

javascript - 如何从数组中提取数字序列?

javascript - 为什么我的 JavaScript 不改变这个 while 循环中的背景颜色?

java - 在被认为是 "clean"的枚举内部提供函数吗?

java - Java声音文件未播放

java - 将 XML 文件导入 Java 处理时出现 NullPointerException

javascript - 通过 "id” 而不是通过 “value” 属性为表单输入分配值

c# - 按顺序调用多个 API 来检索和传递 token C#

function - Delphi - 编写带有函数的 .pas 库

python - 列出给定类的层次结构中的所有基类?