Skip to main content

Objects & Classes

Object Creation

// Object literal
const person = {
name: 'John',
age: 30,
greet() {
return `Hello, I'm ${this.name}`;
},
};

// Constructor function
function Person(name, age) {
this.name = name;
this.age = age;
}

// Object.create
const proto = {
greet() {
return 'Hello';
},
};
const obj = Object.create(proto);

Object Methods

// Property access
person.name; // Dot notation
person['age']; // Bracket notation

// Property manipulation
Object.keys(person); // ["name", "age", "greet"]
Object.values(person); // ["John", 30, function]
Object.entries(person); // [["name", "John"], ["age", 30], ...]

// Property descriptors
Object.defineProperty(obj, 'prop', {
value: 42,
writable: false,
enumerable: true,
configurable: true,
});

// Object copying
const shallow = { ...person };
const deep = JSON.parse(JSON.stringify(person));

Destructuring

// Object destructuring
const { name, age } = person;
const { name: fullName, age: years } = person; // Rename
const { name, age, city = 'Unknown' } = person; // Default

// Nested destructuring
const user = {
id: 1,
profile: {
name: 'John',
settings: { theme: 'dark' },
},
};
const {
profile: {
name,
settings: { theme },
},
} = user;

Prototypes & Inheritance

// Prototype chain
function Animal(name) {
this.name = name;
}

Animal.prototype.speak = function () {
return `${this.name} makes a sound`;
};

function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}

// Set up inheritance
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.speak = function () {
return `${this.name} barks`;
};

const dog = new Dog('Rex', 'German Shepherd');
dog.speak(); // "Rex barks"

Classes

Class Declaration

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}

greet() {
return `Hello, I'm ${this.name}`;
}

get info() {
return `${this.name} is ${this.age} years old`;
}

set newAge(age) {
this.age = age;
}

static species() {
return 'Homo sapiens';
}
}

// Inheritance
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}

study() {
return `${this.name} is studying`;
}
}

Private Fields (ES2022)

class BankAccount {
#balance = 0;

deposit(amount) {
this.#balance += amount;
}

get balance() {
return this.#balance;
}

#validateAmount(amount) {
return amount > 0;
}
}

Static Members

class MathUtils {
static PI = 3.14159;

static add(a, b) {
return a + b;
}

static #privateHelper() {
return 'internal logic';
}
}

MathUtils.add(2, 3); // 5
MathUtils.PI; // 3.14159

Object Property Features

Property Shorthand

const name = 'John';
const age = 30;

// Property shorthand
const person = { name, age }; // Same as {name: name, age: age}

// Method shorthand
const obj = {
// Instead of: getName: function() { return this.name; }
getName() {
return this.name;
},
};

Computed Properties

const propName = 'dynamic';
const obj = {
[propName]: 'value',
[`${propName}Method`]() {
return 'method result';
},
};

console.log(obj.dynamic); // "value"
console.log(obj.dynamicMethod()); // "method result"

Advanced Object Patterns

Factory Functions

function createPerson(name, age) {
return {
name,
age,
greet() {
return `Hello, I'm ${this.name}`;
},
celebrateBirthday() {
this.age++;
return `Happy birthday! Now ${this.age} years old.`;
},
};
}

const john = createPerson('John', 30);

Module Pattern

const counterModule = (function () {
let count = 0;

return {
increment() {
return ++count;
},
decrement() {
return --count;
},
getCount() {
return count;
},
};
})();

counterModule.increment(); // 1
counterModule.getCount(); // 1

Mixins

const CanFly = {
fly() {
return `${this.name} is flying`;
},
};

const CanSwim = {
swim() {
return `${this.name} is swimming`;
},
};

class Bird {
constructor(name) {
this.name = name;
}
}

// Apply mixins
Object.assign(Bird.prototype, CanFly);

const eagle = new Bird('Eagle');
eagle.fly(); // "Eagle is flying"