javascript - ES6 classes: is it possible to access the constructor of a child class from the parent? - Stack Overflow

Using ES6 class syntax, is it possible to create a new instance of the current class from the parent? F

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.

Share Improve this question asked Feb 10, 2017 at 14:31 mkrausemkrause 1,3991 gold badge10 silver badges11 bronze badges 4
  • 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
Add a ment  | 

2 Answers 2

Reset to default 8

You 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信