Middle+
What will happen if instead of a class, a regular object with the same methods is used (without strict mode)?
sobes.tech AI
Answer from AI
If instead of a class, a regular object with the same methods is used (without strict mode), the main differences will be in behavior when creating instances and inheritance mechanisms.
A class in JavaScript is syntactic sugar over prototypal inheritance. When using a class, you can create new objects via new, which automatically inherit methods from the class prototype.
If you simply create an object with methods, then:
- You cannot use
newto create instances because the object is not a constructor. - Methods will just be properties of the object, not a prototype for new objects.
- There is no automatic binding of
thiswhen calling methods through instances, since there are no instances.
Example:
// Class
class User {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}`);
}
}
const u = new User('Alice');
u.greet(); // Hello, Alice
// Regular object
const userObj = {
name: 'Bob',
greet() {
console.log(`Hello, ${this.name}`);
}
};
userObj.greet(); // Hello, Bob
// But you cannot do new userObj()
// TypeError: userObj is not a constructor
Thus, a class is convenient for creating multiple similar objects with shared methods and inheritance, while an object is just a set of properties and functions.