Consider this example code:
class Test {
say() {
console.log("I'm a test.");
}
}
let TestFromClass = new Test();
let TestFromObject = {
say() {
console.log("I'm also a test.");
}
};
TestFromClass.say(); // Output: I'm a test.
TestFromObject.say(); // Output: I'm also a test.
I understand that it's possible to create objects, such as TestFromObject
, without first creating a class with the class
keyword. Is class
necessary at all? Is there a difference between these two kinds of objects? If so, what effect does it have to use class
explicitly?
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);
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());