javascriptfunctionclassoopprototype

Setting Prototype Object of a Constructor function vs Prototype Object of a Class In JS?


So, I was learning about Prototypes and OOPS concept in javascript. WHile playing around with prototypes, I came across this weird behaviour(weird because I am unaware of the concepts :) ). The code for the same is as follows:

let o1 = {
  sayHi() {
    console.log("hi");
  },
  sayBye() {
    console.log("Bye");
  }
}

function ex() {
  this.naam = "ash";
}

ex.prototype = o1;
let o2 = new ex();

console.log(o2);

class example {
  constructor(a) {
    this.naam = a;
  }
}

example.prototype = o1;
const e = new example("ash");
console.log(e);

Output on console looked something like this: Output for above code

I thought both the outputs will look the same in terms of their prototype but it turned out that directly assigning an object to prototype object of class doesn't seem to work at all.

I know that this is a bad practice and a new prototype shall be added to the prototype of the class using something like Object.setPrototypeOf(example.prototype, o1), but just for better understanding, I came up with this question. Would be really grateful if anyone could help me out.


Solution

  • The prototype property on a class is not writable:

    class Example {}
    
    console.log(Object.getOwnPropertyDescriptor(Example, "prototype"));

    Whereas it is writable in the case of a constructor function:

    function Example() {}
    
    console.log(Object.getOwnPropertyDescriptor(Example, "prototype"));

    This is why assigning to the prototype property works in the case of a constructor function but doesn't work with a class.

    If you need to add a method on the prototype object of a class, define it inside the class:

    class Example {
      sayHi() {
        console.log("hi");
      }
      sayBye() {
        console.log("Bye");
      }
    }
    
    const e = new Example();
    console.log(Object.getOwnPropertyNames(Example.prototype));