由于您的问题主要是风格上的(不想用一堆声明填充构造函数),因此也可以从风格上解决。
The way I view it, many class based languages have the constructor be a function named after the class name itself. Stylistically we could use that that to make an ES6 class that stylistically still makes sense but does not group the typical actions taking place in the constructor with all the property declarations we're doing. We simply use the actual JS constructor as the "declaration area", then make a class named function that we otherwise treat as the "other constructor stuff" area, calling it at the end of the true constructor.
"use strict";
class MyClass
{
// only declare your properties and then call this.ClassName(); from here
constructor(){
this.prop1 = 'blah 1';
this.prop2 = 'blah 2';
this.prop3 = 'blah 3';
this.MyClass();
}
// all sorts of other "constructor" stuff, no longer jumbled with declarations
MyClass() {
doWhatever();
}
}
在构造新实例时,两者都将被调用。
有点像有两个构造函数,你可以把声明和其他你想要执行的构造函数动作分开,并且在风格上让它不太难以理解这是在发生什么。
我发现当处理大量声明和/或大量需要在实例化时发生的操作并希望保持这两种思想彼此不同时,使用这种风格很好。
NOTE: I very purposefully do not use the typical idiomatic ideas of "initializing" (like an init() or initialize() method) because those are often used differently. There is a sort of presumed difference between the idea of constructing and initializing. Working with constructors people know that they're called automatically as part of instantiation. Seeing an init method many people are going to assume without a second glance that they need to be doing something along the form of var mc = MyClass(); mc.init();, because that's how you typically initialize. I'm not trying to add an initialization process for the user of the class, I'm trying to add to the construction process of the class itself.
While some people may do a double-take for a moment, that's actually the bit of the point: it communicates to them that the intent is part of construction, even if that makes them do a bit of a double take and go "that's not how ES6 constructors work" and take a second looking at the actual constructor to go "oh, they call it at the bottom, I see", that's far better than NOT communicating that intent (or incorrectly communicating it) and probably getting a lot of people using it wrong, trying to initialize it from the outside and junk. That's very much intentional to the pattern I suggest.
对于那些不想遵循这种模式的人来说,完全相反的方法也可以奏效。在开始时将声明传递给另一个函数。也许可以命名为“properties”或“publicProperties”之类的。然后把剩下的东西放在普通构造函数中。
"use strict";
class MyClass
{
properties() {
this.prop1 = 'blah 1';
this.prop2 = 'blah 2';
this.prop3 = 'blah 3';
}
constructor() {
this.properties();
doWhatever();
}
}
请注意,第二种方法可能看起来更干净,但它也有一个固有的问题,即当使用该方法的类扩展另一个类时,属性会被覆盖。为了避免这种情况,您必须为属性提供更唯一的名称。我的第一个方法没有这个问题,因为它的伪构造函数的一半是以类唯一命名的。