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.

Caution noteCaution

The features described below are supported only in Edge mode.

In Edge mode, you can use shorthand syntax to create an object literal.

var key = 'a';
var value = 5;

// Older version
var obj1 = {
    key: key,
    value: value
};

// Edge mode
var obj2 = {key, value};

console.log(obj2);

// Output:
// [object Object] {key: "a", value: 5}

The following example shows the use of shorthand syntax to define methods in object literals.

// Older versions
var obj = {
    method1: function() {},
    method2: function() {}
};

// Edge mode
var obj = {
    method1() {},
    method2() {}
};

You can also set property names dynamically in object literals in Edge mode. The following code example creates a property name for an object dynamically using the set syntax.

var propName = "prop_42";

var obj = {
    value: 0,
    set [propName](v) {
        this.value = v;
    }
}

console.log(obj.value);
// Runs the setter property.
obj.prop_42 = 777;
console.log(obj.value);

// Output:
// 0
// 777

The following code example creates a property name for an object dynamically using the get syntax.

var propName = "prop_42";

var obj = {
    get [propName]() {
        return 777;
    }
}

console.log(obj.prop_42);

// Output:
// 777

The following code example creates a computed property using arrow function syntax to append 42 to the property name.

var obj = {
    [ 'prop_' + (() => 42)() ]: 42
};
Show:
© 2015 Microsoft