0

I'm having trouble finding information about the difference between these two ways of writing classes. Do they behave differently? why might you use one over the other ?

var Greeter = function(greeting) {
    this.greeting = greeting;
};

Greeter.prototype.greet = function() {
    console.log(this.greeting);
}

var hello = new Greeter("hello");
hello.greet();

versus:

class Greeter {
    greeting;

    constructor(greeting) {
        this.greeting = greeting;
    }
};

Greeter.prototype.greet = function() {
    console.log(this.greeting);
}

var hello = new Greeter("hello");
hello.greet();
user3006927
  • 484
  • 4
  • 15
  • 1
    [There's plenty of differences for classes/functions](https://stackoverflow.com/questions/46820121/in-javascript-what-are-the-differences-between-a-class-and-a-constructor/46821201#46821201). I haven't kept that answer up to date. There's also fields and private fields nowaday. – MinusFour Sep 08 '22 at 01:37
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_Classes – Pointy Sep 08 '22 at 01:37
  • 1
    Apart from technical details, the two versions of your code don't behave that differently. However `greeting = null;` is superfluous (you wouldn't have written `this.greeting = null;` in the constructor either) and you should have declared `greet` using method syntax in the `class`. In general, `class` syntax is more modern and idiomatic, you should prefer it if your intention is to create a class. – Bergi Sep 08 '22 at 01:40
  • Makes, sense, I'll remove the null. @Bergi why should you use the method syntax to declare greet? Doesn't that make the method get copied over for each object instantiated as opposed to once when you use Class.prototype.method? – user3006927 Sep 08 '22 at 01:45
  • 1
    @user3006927 No, proper method declarations in the `class` body (not class fields, not in the constructor) are just normal prototype methods, just much nicer syntax – Bergi Sep 08 '22 at 01:56

0 Answers0