I'm trying to understand 'classes' in JavaScript.
Usually emulating classes in JavaScript looks something like this:
function MyClass(someParameter) {
this.someValue = someParameter;
this.someOtherValue = "green";
}
MyClass.prototype.someMethod = function() {
console.log("Hello!");
};
While the non-function members are set inside the constructor, the method is added outside of the constructor, to the .prototype
property of the constructor.
I'd like to understand why. Why not create the methods inside the constructor, just like the rest of the members? Meaning:
function MyClass(someParameter) {
this.someValue = someParameter;
this.someOtherValue = "green";
this.someMethod = function() {
console.log("Hello!");
}
}