Search code examples
javascriptecmascript-6prototype

Instance methods missing from prototype object


When declaring a class (using the ECMAScript 2015 class) syntax, where are the methods that are defined as part of the class stored? I was expecting to find them on the prototype-object, but for some reason I could not access them in the following sample:

class MyClass {
  constructor() {
    this.a = function() {return ("a");};
  }

  b() { return ("b"); }
}

MyClass.prototype.c = function() { return ("c"); }

const m = new MyClass();

// Sanity check: All three functions are callable and return correct results
console.log(m.a()); // "a"
console.log(m.b()); // "b"
console.log(m.c()); // "c"

// Expected: The only property of the object m itself is a
console.log(Object.keys(m)); // ["a"]

// Unexpected: Where is b?
console.log(Object.keys(Object.getPrototypeOf(m))); // ["c"]
console.log(Object.keys(MyClass.prototype)); // ["c"]

The b-function must be somewhere (it is clearly callable), but where? I tested this behavior node 9.5.0 and Firefox 58.0.1


Solution

  • Object.keys only shows enumerable properties. The properties defined on the prototype by class aren’t enumerable.

    console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(m)));