In JavaScript, an object literal is a way to create an object by directly specifying its properties and values within curly braces {}
. It's a simple and concise syntax for creating objects without needing to define a separate constructor function.
Here's an example of an object literal:
var person = {
name: "John",
age: 30,
city: "New York"
};
In this example, person
is an object created using an object literal. It has three properties: name
, age
, and city
, each with their respective values.
But, if you want to create an object using a constructor function in JavaScript, you can define a function and then use the new
keyword to instantiate an object from that function. Here's an example:
// Constructor function
function Person(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
}
// Creating an object using the constructor
var person1 = new Person("John", 30, "New York");