Agenda

JavaScript Objects Overview

Creating Objects/Classes

JSON

Objects Overview | Creating Objects/Classes [ Initializer, Create, Constructor, Class ]

Arrays/Objects as Properties | Working with Objects | JSON | Worksheet

JavaScript has objects just like other object-oriented programming languages do (like Java). But objects in JavaScript work a bit differently, and are coded differently, than what you’ve learned in your Java classes. Some things are easier, some are a bit more complicated.

In the previous week, we learned about indexed collections or ordered collections (arrays). Objects are often referred to as keyed collections. They’re actually a lot like arrays, except instead of indexes, they use unique keys, or key-value pairs.

Key-Value Pairs

A Key-Value pair in an object is often referred to as a property. For example, if you have an object called Student, that Student object might have properties for student ID, first name, and last name.

Student
- studentId : long

That’s part of a UML class diagram like those you would have seen when learning Java. it shows that Student has three private data members: studentId, firstName, and lastName.

In JavaScript, we would say that the Student object has three properties.

The property names are called keys.

A Key-Value pair is the property name and it’s value. For example studentId = 111222333 is a key-value pair where the key is studentId and the value is 111222333.

Classes Vs. Objects

In Java, you learned that classes are templates, and that an object is an instance of a class.

In JavaScript, there aren’t any classes. In fact, everything in JavaScript that isn’t a primitive, is an object. Even indexed collections (arrays) are objects.

Interestingly, since functions are values (see week 4), this means you can also use a function in place of an object!

JavaScript is a **prototypal** object oriented language: you don’t need classes. You create objects by simply starting with an empty object and adding properties and methods to it. Objects can be extended by adding new properties and methods to an instance (thus, inheritance).

Details of the object model - JavaScript | MDN