Objects
JavaScript Reference: Object
A reference to the JavaScript Object type and its built-in properties and methods, from creating objects to static helpers like Object.keys() and seal().
Anything that is not a primitive (string, number, boolean, symbol, null, or undefined) is an object. Arrays and functions are objects too.
Create an object
The object literal is the form you will use most:
const person = {}
typeof person //object
These are equivalent ways to make a plain object:
const person = Object()
const person = new Object()
const car = Object.create()
Initialize properties inline:
const person = {
age: 36,
name: 'Flavio',
speak: () => {
//speak
}
}
const person = Object({
age: 36,
name: 'Flavio',
speak: () => {
//speak
}
})
const person = new Object({
age: 36,
name: 'Flavio',
speak: () => {
//speak
}
})
You can also use a constructor function:
function Car(brand, model) {
this.brand = brand
this.model = model
}
Then instantiate it:
const myCar = new Car('Ford', 'Fiesta')
myCar.brand //'Ford'
myCar.model //'Fiesta'
Properties, methods, and references
Objects store properties: a name and a value. Values can be any type, including nested objects.
When a property value is a function, we call it a method.
Objects can inherit properties from other objects. We cover that in prototypal inheritance.
Objects are passed by reference. Primitives copy by value:
let age = 36
let myAge = age
myAge = 37
age //36
Two variables can point at the same object:
const car = {
color: 'blue'
}
const anotherCar = car
anotherCar.color = 'yellow'
car.color //'yellow'
Built-in Object properties
The Object constructor exposes two properties:
lengthalways equal to1prototypethis points to the Object prototype object: the object that all other objects inherit from. Check the prototypal inheritance post for more.
Static methods
Static methods live on Object itself. Instance methods run on a particular object.
Static helpers keep related utilities namespaced instead of polluting globals:
Object.assign()*ES2015Object.create()Object.defineProperties()Object.defineProperty()Object.entries()*ES2017Object.freeze()Object.getOwnPropertyDescriptor()Object.getOwnPropertyDescriptors()Object.getOwnPropertyNames()Object.getOwnPropertySymbols()Object.getPrototypeOf()Object.is()*ES2015Object.isExtensible()Object.isFrozen()Object.isSealed()Object.keys()Object.preventExtensions()Object.seal()Object.setPrototypeOf()*ES2015Object.values()
Instance methods
Every plain object inherits these methods on its prototype:
Create { name: 'Flavio' }, copy it to a second variable, change name through the copy, and log the original. That one experiment shows reference sharing clearly.
Lesson completed