Practice: Creating objects with JavaScript

Return to article

Follow these solution steps to check your work.

Solution 1: Create objects using the Object function

Define a name for the object you are creating, and set it equal to a new Object using the new keyword followed by the Object function. After the object is instantiated, add a property using dot syntax, and set it equal to any value you choose. Use dot syntax to add a method name, and set it equal to a function to add a method to your new object. Listing 1 shows the code.

Listing 1. Create a new object using the Object function, and add a property and method
var myObject = new Object();
myObject.myProp = "my prop value";
myObject.myMethod = function() {
  // Add custom JavaScript code here
}

Solution 2: Create objects using literal notation

Define a name for the object you are creating, and set it equal to an open and closing curly brace ({}) to create the new object. Within the open and closing brackets, add a property and set it to any value you choose. With literal notation, you need to follow any properties or methods with a comma (,) if you are adding more properties or methods. Because you're adding a method after this new property, add a comma. To add the new method, define a name for the method and set it to a function that will contain custom JavaScript code. Listing 2 shows the code.

Create a new object using the literal notation and add a property and method
var myObject = {
  myProp: "my prop value",
  myMethod: function() {
    // Add custom JavaScript code here
  }
}

Solution 3: Create objects using the object constructor and prototypes

To create an object using the Object constructor, you simply create a function with the name of your object. Within this function, you can define properties using the this keyword. To add methods to this new object, you use the prototype keyword. After the object has been constructed, you can instantiate the object as many times as you want simply by using the new keyword. Listing 3 shows the code.

Listing 3. Create a new object using the object constructor and prototypes, and add a property and method
function myObject() {
  this.myProp = "my prop value";
}
myObject.prototype.myMethod = function() {
  // Add custom JavaScript code here
}

var newObject = new myObject();

Return to article