In Javascript, a constructor function contains a .prototype
property that contains any methods defined for that object (either with direct assignment to the prototype in ES5 or with the class
keyword in ES6).
Then, when you instantiate a new object with that constructor, the object is given a pointer to the prototype. When a method is called on that object, the Javascript interpreter will look first on the object itself for a property with that name and, if not found there, it will then go search the prototype chain.
So, the only thing that is "copied" to a newly created object in Javascript is a pointer to the prototype. And, this works identically in ES5 and ES6. The class
syntax in ES6 is just new syntax for doing what we were manually doing already in ES5 (assigning methods to the prototype object).
In fact, you can even get the prototype if you want with Object.getPrototypeOf()
. It's important to realize that the new object contains a pointer to the prototype object (not a copy). If subsequent changes are made to the prototype object, it is "live" and all instantiated objects before or after will see that change.
class Car {
constructor(brand, model) {
// initialize instance data
this.brand = brand;
this.model = model;
}
goForward() {
console.log("goForward");
}
goBackward() {
console.log("goBackward");
}
}
let c = new Car("Toyota", "Corolla");
console.log(Object.getPrototypeOf(c)); // shows the two methods goForward, goBackward
console.log(c.brand); // "Toyota"
Now if Car class has goForward() or goBackward() methods, all of them will get copied to myCar object.
The new object is given a pointer to the prototype. The methods are not copied individually.
According to my understanding, this copying of data and methods is the ultimate requirement if we want to use class-inheritance as a design pattern.
This is just not true. Inheritance does not require copying of all methods to the new object. There are actually many different ways to achieve proper inheritance. Javascript uses a prototype. C++ uses compile time binding. I don't know the internals of Java myself, but this post refers to a method table that each object in Java is given a pointer to.
Does the new ES6 class-based structure brings this thing into picture?
ES6 does not change how inheritance works internally in Javascript. ES6 just introduces the class
syntax which is a different way of declaring an object constructor and methods, but it results in the same internal structure as the way we manually declared methods on the prototype in ES5.