I am wondering what's the difference between setting methods via Class body vs prototype binding in JS. (if any)
I am currently working on Eloquent JavaScript example and I was surprised when author firstly created a class with bunch of methods inside its body and then created another method with className.prototype.methodName = function(){}
class Cat {
constructor() {
}
method1() {
console.log("m1");
}
}
Cat.protoype.method2 = function() {
console.log("m2");
}
The most obvious difference is:
You can mutate the prototype of every class with the second method (including native ones), while the first syntax only works for declaring your own classes (but on the other hand it keeps things clean & structured).
There are other differences, that you can ignore in most cases:
1) Class methods are not enumerable, while setting a property directly makes it enumerable.
This would be more equivalent to the class syntax:
Object.defineProperty(Cat.protoype, "method2", {
value() {
console.log("m2");
},
enumerable: false, // it's the default value, this is just for clarity
writable: true,
configurable: true,
});
2) super
is only accessible in methods added during declaration (both in objects and classes) of the object / class itself.
3) The .name
of the function is "test" in the first, and "anonymous" in the second case. That can be changed by making the function non anonymous, e.g. function method2() { ... }