JavaScript: Objects

Notes Home

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. In addition to objects that are predefined in the browser, you can define your own objects.

MDN Objects guide

We've seen some objects already, like when we typed document into the console or when we logged the event data from a mouse click.

We can write our own objects as a way of experimenting with how objects work.

Dot notation

var train = {};

Objects are declared with curly brackets.

train.color = "blue";
train.speed = 100;
train.numberOfPassengers = 400;
train.distance = 25;
train.origin = "New York";
train.destination = "Boston";
console.log(train);

Objects are a model for the primary data structure of JavaScript. It is how we organize and access information and functionality.

Bracket notation

var anotherTrain = new Object();
anotherTrain["color"] = "red";
anotherTrain["line"] = "2";

Any string can be used as an key or property name, and any variable can be saved in each property, a number, string, function, array, object or even null or "" (empty string).

Object notation

var train = {
	speed: 60,
	numberOfPassengers: 500,
	distance: 100,
	origin: "Seattle",
	destination: "San Francisco"
};
console.log(train);

Object constructors

Objects can be defined with contructor functions.

Per convention, constructor functions are named with capital letters, to distinguish them from other functions.

The keyword new is used to create a new object.

function Train(speed, origin, destination) {
	this.speed = speed;
	this.origin = origin;
	this.destination = destination;
}
var lineNine = new Train(50, "Century Ave", "Xiaonanmen");

The new object is referred to as an instance.

Each instance can be extended.

lineNine.numPassengers = 100;

The original contructor can be modified using the .prototype property.

Train.prototype.color = null;
lineNine.color = "blue";