Objects-basis
An object is like a cabinet with signed files. Every piece of data is stored in its file by the key.
key
is a string (also called a “property name”), andvalue
can be anything.
An empty object (“empty cabinet”) can be create using one of two syntaxes:
1 | let user = new Object(); // "object constructor" syntax |
Literals and properties
1 | let user = { // an object |
1 | // get property values of the object: |
To remove a property, we can use the delete
operator:
1 | delete user.age; |
When we write a multiword key name, like:
1 | let user = { |
We should notice that the dot access doesn’t work for it now:
1 | user.likes birds = true // FAULT !!! |
This time, we need square bracket notation:
1 | let user = {}; |
And with sqare bracket notation, we could obtain the property name as the result of any expression - as opposed to a literal string - like from a variable as follows:
1 | let key = "likes birds"; |
And then comes this:
1 | let user = { |
But here the dot notation doesn’t work.
1 | let key = "name"; |
Computed properties
We can use square brackets in an object literal, when creating an object. That’s called computed properties.
1 | let fruit = prompt("Which fruit to buy?", "apple"); |
Property value shorthand
We could write this:
1 | function makeUser(name, age) { |
The “for..in loop”
1 | let user = { |
Ordered like an object
When we loop over an object, the integer properties are sorted from lower to higher, other then appear in creation order.
For instance:
1 | let codes = { |
This
1 | const person = { |
The this
keyword typically refers to the curren t object the code is being executed in.
Constructors
A constructor is just a function called using the new
keyword. When you call a constructor, it will:
- create a new object.
- bind
this
to the nwe object, so you can refer tothis
in your constructor code. - run the code in the constructor.
- return the new object.
Constructors, by convention, start with a capital letter and are named for the type of the object they create. So we could write our example like this:
1 | function Person(name) { |
Differences between objects and primitives
Besides the formal differences, there are also som technical differences which affect how we use each data type. When you define a primitive variable, it will contain a copy of the informatino provided to it.
On the other hand, when you define an object variable, it will contain a reference to the object provided to it:
1 | let data = 42; |