Using ES6 class syntax, is it possible to create a new instance of the current class from the parent? For example:
class Base {
withFoo() {
return new self({ foo: true });
}
}
class Child extends Base {}
(new Child()).withFoo();
I'm looking for something similar to PHP's new self()
syntax.
Using ES6 class syntax, is it possible to create a new instance of the current class from the parent? For example:
class Base {
withFoo() {
return new self({ foo: true });
}
}
class Child extends Base {}
(new Child()).withFoo();
I'm looking for something similar to PHP's new self()
syntax.
- 1 In JavaScript, the "class" is the constructor. – castletheperson Commented Feb 10, 2017 at 14:39
- What's the reason for wanting this behavior? – Mjh Commented Feb 10, 2017 at 14:41
- @Mjh Any situation where you want the base class to contain custom constructors (e.g. factory methods). In my case, I need a method to operate on immutable objects from the base class. – mkrause Commented Feb 10, 2017 at 15:05
- Since constructor can only be one, you can't have custom constructors, you can only have 1 constructor. You basically want PHP's statics that can pass different arguments to the class' constructor, thus instantiating the object with different parameters. Did I get it right or am I wrong? You have a problem that you're trying to solve, so it might be better to ask about that problem instead of perceived solution, which is also known as XY problem and I think we might have an XY problem here. – Mjh Commented Feb 10, 2017 at 15:14
2 Answers
Reset to default 8You can access the current instance's constructor via this.constructor
.
In a static methods you can use this (which then represents a class reference) to instanciate objects of child classes.
Working Typescript code:
class Base {
foo: boolean
constructor(param: {foo: boolean}) {
this.foo = param.foo;
}
static withFoo() {
return new this({foo: true}); // key line: use this instead of self in _static_ methods
}
}
class Child extends Base { }
const child = Child.withFoo(); // will return an instance of Child with foo set to true
console.log(child); // Child {foo: true}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745344482a4623479.html
评论列表(0条)