1

class Parent {
    print() {
        console.log('hey i am parent');
    }
}

class Child extends Parent {
    constructor() {
        super();
    }
    print() {
        console.log('hey i am child');
    }
}

x = new Parent();
console.log(Object.getPrototypeOf(x))
x.print();

Though the [[prototype]] of x is an empty object but still It can access the print() function which is defined in class Parent.

I cannot understand why Object.getPrototypeOf(x) is an empty object.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247

2 Answers2

3

It's in there, just non-enumerable. Try this:

Object.getOwnPropertyNames(Object.getPrototypeOf(x));

// ["constructor", "print"]

class Parent {
  print() {
    console.log('hey i am parent');
  }
}

class Child extends Parent {
  constructor() {
    super();
  }
  print() {
    console.log('hey i am child');
  }
}

x = new Parent();
console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(x)));
x.print();
Rajesh
  • 24,354
  • 5
  • 48
  • 79
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
1

What makes you think it's empty? It does have constructor and print properties, they are however not enumerable and not displayed by default on the console. (And of course it does have a [[prototype]] link to Object.prototype, but how/whether that is displayed depends on your console as well).

To inspect them, have a look at Get functions (methods) of a class.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • be this the case `function Parent() { } Parent.prototype.print = () => { console.log('printing'); } x = new Parent() console.log(Object.getPrototypeOf(x)); ` this prints an object with **print** as its property. I cannot seem to understand why is this not the case above – amritdevilo Feb 03 '17 at 06:42