Picture

Hi, I'm Travis Faas.

Teacher.

Objects

Objects

Objects are a way of storing a set of related variables that are a different, but associated with each other. Typically they are used to model something. Here is an example, in english.

We might make an object to describe a chair. It would have a set number of traits:

  • a height
  • a color
  • a weight
  • a number of legs
  • perhaps a number of wheels

And onward.

Making an object

Here is that same object, in Typescript.

	var someChair = {
		height: 23,
		color: "#FF0000",
		weight: 10,
		numLegs: 4
	};

Some things to note: objects are enclosed in culry brackets, and they are a set of name: value pairs, seperated by commas.

Access object properties

Use a dot.

	var someChair = {
		height: 23,
		color: "#FF0000",
		weight: 10,
		numLegs: 4
	};

	console.log(someChair.height); //23
	console.log(someChair.weight); //23

Some nomenclature: variables that exist within a class are called properties.

And yes, properties work just like variables too

	var someChair = {
		height: 23,
		color: "#FF0000",
		weight: 10,
		numLegs: 4
	};

	someChair.height = 10; //smaller chair

Object Constructor

Objects are great for modeling a singular thing. If you want to make multiple of some object, it makes more sense to move on to a class.

Let’s make a chair class, because we’re not very creative.

function Chair() {
	this.height = 1;
	this.color = "#FF0000";
	this.weight = 20;
	this.numLegs = 3;
}

A class is just a specification for an object, however. If we want to make an actual version of it, we need to make an instance of that class.

Making an instance of an object

  1. Use the new keywork
  2. Write the name of the class
  3. Put paranthesis after the name
function Chair() {
	this.height = 1;
	this.color = "#FF0000";
	this.weight = 20;
	this.numLegs = 3;
}

var someChair = new Chair();
someChair.height = 23;
someChair.color = "#FF0000";
someChair.weight = 12;

Constructing a class

Sometimes it makes more sense to provide a series of values that the class will put into its properties by default. A constructor is a function (called a method when it appears inside of a class), that is run right when the class is instantiated (this happens when you see the new keyword).

In this case, we take a bunch of values, and store them in the class’ properties.

function Chair() {
	this.height = 1;
	this.color = "#FF0000";
	this.weight = 20;
	this.numLegs = 3;
}

var someChair = new Chair(23, "#FF0000", 10, 4);

console.log(someChair.height); //23