Creating Objects (JavaScript)

There are a number of ways you can create your own objects in JavaScript. You can directly instantiate an Object Object (JavaScript) and then add your own properties and methods. Or you can use object literal notation to define your object. You can also use a constructor function to define an object. For more information about using constructor functions, see Using Constructors to Define Types.

The following code shows how to instantiate an object and add some properties. In this case only the pasta object has the grain, width, and shape properties.

var pasta = new Object();
pasta.grain = "wheat";
pasta.width = 0.5;
pasta.shape = "round";
pasta.getShape = function() { 
    return this.shape; 
};
document.write(pasta.grain);
document.write("<br/>");
document.write(pasta.getShape());

// Output:
// wheat
// round

You can also use object literal notation when you want to create only one instance of an object. The following code shows how to instantiate an object by using object literal notation.

var pasta = {grain: "wheat", width: 0.5, shape: "round"};

You can also use an object literal inside a constructor.

Show:
© 2014 Microsoft