I am learning about prototypal inheritance and I recently learned that if I use a factory function to create objects that all have methods, this results is unnecessary amounts of memory being used and that by setting the methods on the prototype, all objects generated from a factory function will share the same functions in memory. The same goes for a constructor function.
With that said, when I generated an object using the class syntax, the method1 and method2 methods by default are showing up in the prototype (__proto__) of the generated object. I was expecting to have to do manually like you would with a constructor function...
Test.prototype.get = somGetFunctionDefinedOutsideOfClass
in order to have the method1 and method2 methods set to the prototype.
Does this mean that if I generate 1 million objects all using the same Class, they all have their prototype set to the same methods and I wouldn't have to set the prototype manually?
const Test = class TestClass {
constructor() {
this.variable = 'testVariable'
}
method1() {
console.log('method1')
}
method2() {
console.log('method2')
}
}
const obj = new Test()
console.log(obj)
obj.method1() // logs: method1
Example using constructor function where methods are not on __proto__
const Test = function TestObjectGenerator() {
this.method1 = function() {
console.log('method1')
}
this.method2 = function() {
console.log('method2')
}
}
const obj = new Test()
console.log(obj)
obj.get()