Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: function is not a constructor (evaluating 'new self.f(1)')

I am trying to use a method as a constructor inside another method. But when I do this I get the following TypeError:

TypeError: function is not a constructor (evaluating 'new self.f(1)')

and example code is:

class C{
        constructor(v){
            this.f(v);
            this.g(v);

        }

        f(v){
            this.v = v;
        }

        g(v){
            var self = this;

            function h(v){
                this.v = v;
                this.w = new self.f(1);
                console.log(this.w);
            }

            new h(1)
        }
    }

var c = new C(1);

is there a reference error with self?

like image 803
Nighel Avatar asked Jul 29 '26 06:07

Nighel


1 Answers

MDN: Method definitions

Method definitions are not constructable All method definitions are not constructors and will throw a TypeError if you try to instantiate them.

One reason why the standard defined it that way, might be that you could use super.foo() within a method definition. But if you would use this method as a constructor then there would be class you inherit from, so a super.foo() would fail.

like image 141
t.niese Avatar answered Jul 31 '26 20:07

t.niese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!