1
class C { foo() {} }
C.prototype.foo // function foo() {}
C.prototype.foo.prototype // undefined - why?

Why is the .prototype property of class methods not set when created via the class method syntax?

Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • What do you expect that to be? – nem035 May 22 '17 at 15:46
  • Because JavaScript attempts to hide/cover-up the power of prototypal inheritance while not providing true classical inheritance with the `class` keyword. It's the worst of both worlds, tbh. – mhodges May 22 '17 at 15:47
  • 1
    I expect it to be an object per a normal function declaration (I think). – Ben Aston May 22 '17 at 15:47
  • 1
    Only constructor functions (and classes) have prototypes. – nem035 May 22 '17 at 15:49
  • `__proto__` (dunder proto) gives a prototype reference, but has been deprecated in favor of `Object.getPrototypeOf()`, which is awkward to chain, but doable. – mhodges May 22 '17 at 15:53
  • Ran the above code in Chrome developer tools and C.prototype.foo.prototype is returning an object. – vabii May 22 '17 at 15:55
  • 2
    @vabii Just ran it in Chrome console, getting undefined. – mhodges May 22 '17 at 15:59
  • @mhodges I must be doing something wrong here - https://jsfiddle.net/vabii/ho2taax8/ – vabii May 22 '17 at 16:06
  • @vabii You didn't "run the above code"... you changed the code and added a definition on the `C` prototype to include a definition for `foo` lol – mhodges May 22 '17 at 16:12
  • @mhodges...oops, my bad.. thanks for clarifying.. – vabii May 22 '17 at 16:14

1 Answers1

3

Because methods (like arrow functions) are no constructors, and don't need a .prototype from which the prototype of instances would be initialised, none will get created.

This is a new feature in ES6, which distinguishes method definitions in object literals and class definitions from usual function definitions.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375