javascript: what's the difference between a function and a class

javascript

Solution

There is technically no class, they're both just functions. Any function can be invoked as a constructor with the keyword `new` and the prototype property of that function is used for the object to inherit methods from.

"Class" is only used conceptually to describe the above practice.

So when someone says to you "make a color class" or whatever, you would do:

function Color(r, g, b) {
    this.r = r;
    this.g = g;
    this.b = b;
}

Color.prototype.method1 = function() {

};

Color.prototype.method2 = function() {

};

When you break it down, there is simply a function and some assignments to a property called `prototype` of that function, all generic javascript syntax, nothing fancy going on.

It all becomes slightly magical when you say `var black = new Color(0,0,0)`. You would then get an object with properties `.r`, `.g` and `.b`. That object will also have a hidden [[prototype]] link to `Color.prototype`. Which means you can say `black.method1()` even though `.method1()` does not exist in the `black` object.

Problem

I am wondering what's the difference between function and class. Both using the keyword function, is there obvious distinction between those two?

Original source

Related problems