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

1

3

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?

Endomorphic answered 17/4, 2017 at 8:8 Comment(8)
"is there a reference error with self?" - No. If you try var x = new this.f(1); just before the function h() declaration you'll see that that doesn't work either.Thomasinethomason
@Thomasinethomason I'm interested in why you can't use a class method as a constructor. I thought the new "class" syntax is just syntactic sugar?Epilepsy
@Derek朕會功夫 - Yeah, I don't know the answer here, I only knew enough to note that the self part wasn't the issue. The class syntax is sugar, but (evidently) it's also a bit more complicated than that...Thomasinethomason
Interesting. this.f.prototype is also undefined, so yea, it can't be used as a constructor.Gang
@Gang Even if I define C.f.prototype = {constructor: C.f} it still doesn't let me use it as a constructor. There must be something more going on.Epilepsy
@Thomasinethomason Apparently the new method definition and class definition in ES6 are not actually just syntactic sugar. Functions created as methods and as arrow functions do not implement the [[Construct]] internal method.Epilepsy
@Derek朕會功夫 I think we could close it as duplicate to your linked question. Because the answer contains all informations.Dicrotic
@Dicrotic They are related but not necessarily a duplicate in my opinion.Epilepsy
D
3

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.

Dicrotic answered 17/4, 2017 at 8:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.