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.
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.
Some nomenclature: variables that exist within a class are called properties.
And yes, properties work just like variables too
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.
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
- Use the new keywork
- Write the name of the class
- Put paranthesis after the name
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.