0

So I was wondering if, with the ES6 class syntax, the methods are kept in memory once per prototype, or once per instance/object.

To demonstrate my findings, here is a short example:

ES5

function X1(x) {
    this.x = x;
}
X1.prototype.getX = function () {
    return this.x;
};

// X1.prototype = { getX: [Function (anonymous)] }

ES6

class X1 {
    constructor(x) {
        this.x = x;
    }

    getX() {
        return this.x;
    }
}

// X1.prototype = { }

Why is the getX method not showing up in the prototye?

MauriceNino
  • 6,214
  • 1
  • 23
  • 60
  • 3
    Are you maybe getting confused because `getX` is a non-enumerable property? It is on the prototype, but depending on how you are enumerating all of the properties, or may or may not show up. – loganfsmyth May 28 '21 at 22:49
  • @loganfsmyth yep that was actually it, thanks! :) – MauriceNino May 28 '21 at 22:55
  • 2
    [ES6 `class` methods are not enumerable](https://stackoverflow.com/q/31423573/1048572), so your console might hide them by default – Bergi May 28 '21 at 23:06
  • @Bergi thanks for the link, got it figured out - was just a little misunderstanding on my part. I'm going through a course right now and got a bit confused with the different concepts and forgot about this right here. – MauriceNino May 28 '21 at 23:21
  • OP said 'I misunderstood', not 'had a typo'! This can be easily misunderstood! Even using the same Class, defining a method in the class def, it won't show when inspecting, eg. `Object.getPrototypeOf()` but adding a method to it's prototype does, eg. `myClass.prototype.newMethod = ...` (even same class, only the latter would show) - and there's not a lot of clear docs as to why methods don't show up (even when using `util.inspect` in node) only when using something doc'd as 'syntactic sugar' - eg. MDN says class definition is equivalent, yet it acts different! – forbiddenera Jul 19 '23 at 10:20

1 Answers1

4

I think you're mistaken:

class X1 {
    constructor(x) {
        this.x = x;
    }

    getX() {
        return this.x;
    }
}

console.log(typeof X1.prototype.getX)
console.log(typeof X1.prototype.foo)
dave
  • 62,300
  • 5
  • 72
  • 93