JavaScript Introduction | Object | Creating Objects
Creating Objects
The following are ways to create objects in JavaScript.
- Using literal notation
- Using a constructor function
- Using the Object.create() method
An object created with one of the methods above and assigned in memory is called an instance.
Creating Objects with Literal Notation
The easiest way to create an object in JavaScript is to use literal notation.
Syntax
var objectName = {
property1Name : property1Value,
property2Name : property2Value,
...
};
Each property connects its name and value with a colon (:), and different properties are separated with commas (,). For a property name, you can use a JavaScript identifier or a string.
var kitty = {
name: "Nabi",
family: "Korean Shorthair",
age: 1,
weight: 1.1
};
document.write("My kitten's name is " + kitty.name + ", and its breed is " + kitty.family + ".");
Creating Objects with a Constructor
You can create and initialize an object by using the new operator.
The method used at this time is called a constructor, and this method initializes the newly created object.
JavaScript predefines and provides constructors for primitive types.
var day = new Date(); // creates an object of the Date type using the new operator.
document.write("This year is " + day.getFullYear() + ".");
As in the example above, you can use constructors provided by JavaScript, or you can write and use your own object constructor function.
Creating Objects with the Object.create() Method
You can also create an object by using the Object.create() method.
The Object.create() method creates a new object with the specified prototype object and properties.
Because this method lets users explicitly specify the prototype object, it is very useful.
Syntax
Object.create(prototypeObject[, property1OfNewObject, property2OfNewObject, ...]);
The first argument of the Object.create() method receives the object to use as the prototype.
The second argument receives information about properties to add to the new object.
var obj = Object.create(null, { // creates a new object using the null prototype
x: { value: 100, enumerable: true }, // and adds an enumerable property representing the x coordinate
y: { value: 200, enumerable: true } // and an enumerable property representing the y coordinate.
});
obj.x; // x coordinate
obj.y; // y coordinate
Object.getPrototypeOf(obj); // returns the object's prototype.