Reputation: 12718
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?
Upvotes: 3
Views: 1880
Reputation: 3179
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.
Upvotes: 4
Reputation: 43661
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:
this
in static methods - but you can use this
in class-level methods in JS "classes"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):
So in JS pseudoclasses are first-class objects whereas in Java they are not.
Upvotes: 6