2

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");
}
3
  • 3
    Not much. class is just newer syntax. Commented Apr 19, 2019 at 16:10
  • Yep, just sugar for the same thing. I don't know of a practical difference. Commented Apr 19, 2019 at 16:11
  • 1
    There is no difference. The class syntax is just syntactic sugar for the later one Commented Apr 19, 2019 at 16:11

2 Answers 2

3

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() { ... }

Sign up to request clarification or add additional context in comments.

3 Comments

Other small differences are the availability of super and the .name of the method, but I doubt the OP cares about that.
@bergi Oh right, haven't thought about that. I'll add that for completeness.
It's non enumerable on the prototype but it's definitely writable
0

I hope this helps: "Changes to the Object prototype object are seen by all objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain. This provides a very powerful although potentially dangerous mechanism to override or extend object behavior."

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.