js "classes" vs classical classes

1.8k Views Asked by At

I asked the following question on why classes are being used in a typically classless prototypal inheritance language like js: class use in a prototypal inheritance-based language

It seems they're "syntatic sugar" because the masses like classes... and that they're just regular js objects in the background.

Now id like to know what the differences are between js fake "classes" and classical classes?

2

There are 2 best solutions below

0
On BEST ANSWER

If I'd compare JS "classes" with classes in Java, the first thing I'd say is that JS "class" is just an object whereas Java class is not.

An object has its own properties/fields/methods. This is also what a JS "class" can have. But a class in Java can not, only instances can.

Some people would probably say "Wait, but how about static fields and methods? I can do a static MyClass.myField field an MyClass.doSomething() method."

Yes, you can. But from my point of view they will just be "placed" in the MyClass namespace, they aren't really properties of the class:

  • You don't have this in static methods - but you can use this in class-level methods in JS "classes"
  • You can't make a class with a static method to implement a certain interface - assuming duck-typing as interface this is no problem in JS

So a Java class with static fields or methods is just a namespace for these fields and methods, nothing more. What makes it even more obvious is the fact that in a static method you can't find out which class you're in (without tricks):

Getting the class name from a static method in Java

So in JS pseudoclasses are first-class objects whereas in Java they are not.

0
On

I can think of this, in class inheritance, the parent objects are locked up. For instance:

class A
{
};

class B extends A
{
};

Here, A's definition is locked up, you can't add new properties once it is inherited.

In Javascript 'classes', you can:

var o = {x:2};
var b = Object.create(o);
o.y = 5;
b.y
>5

Do you see how we added a property after 'inheriting'? This is one difference, objects aren't really locked up(though you can do the locking up of objects by using Object.preventExtensions, Object.seal, Object.freeze), but by themselves the objects can be modified at any point of time and this link to the prototype object is maintained in the child object.