Object lifecycle cheatsheet

Posted November 3, 2016

Taken by Matthew Henry

Firstly, I’d like to apolagize for the lack and timing of these posts. I’ve been busy at work and unfortunately haven’t had the time to write them 😭.

A Javascript object is a standalone entity, with properties and types associated with it. Object properties are basically the same as javascript variables except for they’re attached to objects.

You define a propterty by defining it a value, for example:

1const myCar = new Object();
2myCar.make = 'Ford';

If you define a property but {"don't"} give it a value it becomes undefined, not null. e.g: myCar.color; would return undefined.

To get an item out of an object you can test to see if it has that property, for example, on a project at work, we used this to get a rule's name out of the object

1// The Rule itself
2const rule = {
3 active: true,
4 conditions: [
5 {
6 time: {
7 day: [1, 2, 3, 4],
8 at: '17:30',
9 },
10 },
11 ],
12 uuid: 'some-rule-uuid',
13 consequences: {
14 devices: {
15 '66d5e0ed-5e88-4353-9dd9-318cad3676f9': {
16 'thermostat_setpoint.heat.set': {
17 value: 77,
18 },
19 'thermostat_setpoint.cool.set': {
20 value: 80,
21 },
22 },
23 },
24 },
25 type: 'rule',
26 priority: 1,
27 name: 'test rule',
28};

You can also do if else statements with objects:

1if (cond) var x = { greeting: 'howdy' };

You can even have an object inside another object:

1const myCar = {
2 color: 'red',
3 wheels: 4,
4 engine: {
5 cylinders: 4,
6 size: 2.2,
7 },
8};

Alternatively you can make an object with a constructor function:

1function Car(make, model, year) {
2 this.make = make;
3 this.model = model;
4 this.year = year;
5}
6
7const myCar = new Car('Volvo', 'S40', 2005);