28. What is the difference between object literals and constructor functions?
Object literals and constructor functions are two ways of creating objects in JavaScript. They both allow you to define properties and methods for an object, but there are some key differences between the two:
Object Literals:
An object literal is a set of curly braces that contain property-value pairs, as well as method definitions using the `function` keyword.
Here's an example:
const myObject = {
name: 'John',
age: 30,
sayHello: function() {
console.log('Hello, world!');
}
};
In this case, `myObject` is created as a standalone object and can be accessed using dot notation (e.g., `myObject.name`).
Constructor Functions:
A constructor function is a regular function that has the same name as the object it creates, with an `apply()` or `call()` method called at the end to set up the object's properties and methods. Here's an example:
function MyObject(name, age) {
this.name = name;
this.age = age;
this.sayHello = function() {
console.log('Hello, world!');
};
}
const myObject = new MyObject('John', 30);
In this case, `myObject` is created using the `new` keyword and can be accessed using dot notation (e.g., `myObject.name`).
One of the main differences between object literals and constructor functions is that object literals are simpler and easier to read, while constructor functions provide a more structured way of creating objects with more complex properties and methods. Additionally, constructor functions can be reused to create multiple objects, while object literals cannot.