Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are methods not valid constructors? [duplicate]

Tags:

javascript

Regardless of intent, it's unclear to me why one is valid and other other is not. If someone could point to the relevant part of the language spec, that would be especially helpful.

class Foo {
  bar() {}
}
Foo.prototype.baz = function() {};

const f = new Foo();

new f.baz(); // Valid
new f.bar(); // invalid, throws error
like image 665
pixatlazaki Avatar asked Sep 10 '26 00:09

pixatlazaki


1 Answers

As pointed out in the comments on the original question, the spec defines it this way. A constructor must have the internal [[Construct]]s, and while ordinary function expressions do get this slot set, method definitions do not. This is described in MDN (as another commenter pointed out) as well.

like image 95
pixatlazaki Avatar answered Sep 12 '26 15:09

pixatlazaki