Are JavaScript classes just objects with a prettier name and usability?
JS classes vs JS objects?
class - Are classes necessary in Javascript? What effect do they have on creating objects? - Stack Overflow
Constructors in objects created with classes
class Rectangle {
constructor(height, width) {
this.name = "Rectangle";
this.height = height;
this.width = width;
this.area = height * width;
}
}
console.log(new Rectangle(4, 3).area);
This, to me, just looks as an object called Rectangle, which has a method called constructor with two parameters height and width . Couldn't have done the same with an object constructor?
Hello
What is the difference between JS classes and JS objects? Surprisingly not finding an answer to this on google since the release of ES6. Thanks!
Using new creates a new object whose internal prototype is the class's prototype. For example:
class Test {
say() {
console.log("I'm a test.");
}
}
let TestFromClass = new Test();
console.log(Object.getPrototypeOf(TestFromClass) === Test.prototype);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
This is useful for creating multiple objects. The usual reason to do this is so that each object can have some sort of associated state - generally, the values of its properties. For example, a Person object might have a name and an age property.
However, if there is no data to associate with an instance (as with TestFromClass in the original code), there's not much point having an instance at all. The TestFromObject approach makes much more sense if the purpose is just to collect named functions into a data structure.
That said, it's sometimes desirable to have a class that has some functions associated with it (like say) which don't have anything to do with an instance of its data, while still being able to create an instance - perhaps using other methods on the prototype. This isn't that uncommon, and is done by making the non-instance-related functions static:
class Person {
static canEat() {
return ['apples', 'bananas', 'carrots'];
}
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const p = new Person('Bob', 99);
console.log(p.name);
console.log(Person.canEat());
Run code snippetEdit code snippet Hide Results Copy to answer Expand
A class is more or less just syntactic sugar for a prototype:
// The class way
class Test {
say() {
console.log("I'm a test.");
}
}
// The old fashioned way
function Test() {
}
Test.prototype.say = function () {
console.log("I'm a test.");
};
The difference in both these cases with direct object creation is that the methods belong to the prototype, not directly to the object.
The code TestFromClass.say() must go through the prototype chain to find a say method, while TestFromObject directly has the method.
Other than that, there's no difference.