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:
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.