Difference between inheritance in class-based languages and JavaScript

New to JavaScript?
A lot of you from standard(?) class-based language programmers quite feel differently when you encountered inheritance in JavaScript.
- Let’s say the class is a cook 👩🍳 that creates a bread(instance) 🍞
Inheritance from Class-based language
In a common class-based language, a class Child can be only inherited from another parent or a superclass Parent. And the instance (Bob) from class Child has every method that is defined from class Child. So simply class Child can define the instance, Bob.
However, JavaScript has more flexibility. It’s even more like weird flexibility.
Inheritance from JavaScript
In JavaScript, Instances can inherit to other instances by prototype linking.
If a child instance needed another method from another instance, it can even get it from the other instance.
You may want to see the code now. 👀
let breadObj = {parent: 'parent'};
let croissantObj = {child: 'child'};croissantObj.__proto__ = breadObj // linking parent instance/object to child instance/objectconsole.log(croissantObj.child); //child
console.log(croissantObj.parent); //parentcroissantObj.parent = ‘child’ // change the parent value in child objconsole.log(croissantObj.parent) // child
In JavaScript “__proto__” is not a standard. (but most of all browsers supports this)
What should we do instead, then?
You can use “Object create” instead.
let breadObj = {parent: 'parent'};// let croissantObj = {child: 'child'};
// croissantObj.__proto__ = breadObj // linking parent instance/object to child instance/objectlet croissantObj = Object.create(breadObj); // create new object named croissantObj
croissantObj.child = 'child'; // assign child propertyconsole.log(croissantObj.child); //child
console.log(croissantObj.parent); //parent
croissantObj.parent = 'child' // change the parent value in child obj
console.log(croissantObj.parent) // child
w..wait, so in JavaScript, the instance can inherit its methods and state to other instances, and it can be done in runtime?
“Yes”
One thing to remember is that JavaScript has very similar also at the same time very different behavior to other standard class-based programming languages.