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

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.

Leave a Comment