我正在尝试使用 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/