Skip to content

04. Objects, Maps, Methods and OOP

idavidov13 edited this page Feb 11, 2024 · 3 revisions

Objects

In JavaScript, an object is a collection of key-value pairs, where the keys are strings (or symbols) and the values can be any data type, including other objects, functions, or primitive types. Objects are foundational in JavaScript, as almost everything (including functions, arrays, and even basic data types like numbers and strings) can exhibit object-like behavior.

  • Data values are called properties
  • Function values are called methods

Primitives, objects and the JS Engine

image image

Properties and Methods: Object keys can correspond to properties (data) or methods (functions).

let person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};

Accessing Data: You can access object properties in two ways:

  • Dot notation: objectName.key
  • Bracket notation: objectName["key"]

Dynamic Nature: Objects in JavaScript are dynamic. You can add, modify, or delete properties and methods even after the object is created.

person.age = 30; // Adds a new property "age" to the "person" object
delete person.firstName; // Removes the "firstName" property

'this' Keyword: Within an object method, the this keyword refers to the object that the method belongs to.

console.log(person.fullName()); // Outputs: John Doe

Prototypes: Every object in JavaScript has a prototype from which it inherits properties and methods. This forms the basis for JavaScript's prototypal inheritance.

Object Constructors: While object literals (as shown above) are the most common way to create objects, JavaScript also supports object constructors and the class syntax to define and create objects.

Map

Map is a data structure that can be used to map values to keys
let newMap = new Map();

  • Methods - aMap.size, aMap.set(), aMap.get('keyName'), aMap.has(), aMap.delete(), `aMap.clear()

DATA STRUCTURES OVERVIEW

image image

Classes

Class Definition

  • Structure for objects
  • Classes define:

Data (properties, attributes) Actions (behavior)

  • One class may have many instances (objects)
  • Unlike functions, class declarations are not hoisted!

Class Body

  • The class body contains method definitions
    image
  • The constructor is a special method for creating and initializing an object created with a class
  • Instance properties are defined inside the constructor

Class Methods

  • A class may have methods, which will be available to its instances image

Instance Context

  • this refers to the instance of the class image

Instanceof Operator

  • The instanceof operator returns true if the given object is an instance of the specified class image

Static Methods

  • The static keyword defines a static method for a class class MyClass { static staticMethod() { return 'Static call'; } }
  • Static methods are part of the class and not of its instances console.log(MyClass.staticMethod())
  • They can only access other static methods via this context static anotherStaticMethod() { return this.staticMethod() + ' from another method'; }

Accessor Properties

  • Accessor properties are methods that mimic values

Keywords get and set with matching identifiers They can be accessed and assigned to like properties image

  • Accessors are often used for validation

The setter can verify that a given value meets requirements image

  • Properties without a setter are read-only (cannot be assigned)
  • Getters can be used for a validated or calculated property

DOM Classes

Review: DOM Elements as Class Instances

  • All DOM objects are instances of standard DOM classes

Always created via factory functions, instead of with new
const divElement = document.createElement('div');
console.log(divElement instanceof HTMLDivElement); // true

  • They provide many useful methods and properties

Already seen: addEventListener, appendChild, remove, children, parentNode, textContent, value, etc.

  • cloneNode(deep) creates a duplicate of the selected element

If deep is true, a deep-copy is created
const duplicate = divElement.cloneNode(true);

  • replaceWith() replaces selected element with another
    const span = document.createElement('span');
    divElement.replaceWith(span);
  • before() insert an element before the selected node
  • after() insert element after selected node

Manipulate Element CSS Class

  • classList - is a read-only property that returns a collection of the class attributes of the specified element
    <div id="myDiv" class="container div root"></div>
    const element = document.getElementById('myDiv').classList; //// DOMTokenList(3) ["container", "div", "root", value: "container div root"]
  • classList Methods
    <div id="myDiv" class="container div root"></div>

add() - Adds the specified class values
document.getElementById('myDiv').classList.add('testClass'); remove() - Removes the specified class values
document.getElementById('myDiv').classList.remove('container');
<div id="myDiv" class="div root testClass"></div>

HTML Attributes and Methods

  • getAttribute() - returns the value of attributes of specified HTML element image
  • setAttribute() - sets the value of an attribute on the specified HTML element image
  • removeAttribute() - removes the attribute with the specified name from an HTML element image
  • hasAttribute() - method returns true if the specified attribute exists, otherwise it returns false image

Combining Elements and Behavior

  • Classes can be used to encapsulate elements and behavior

Store references to DOM elements Provide event handlers Methods that manipulate the elements

  • This is called the Component Pattern

Used in many JS frameworks, such as React, Vue, Angular Used in the Custom Web Component API

Build-in Collections

What is a Map?

  • A Map collection stores its elements in insertion order
  • A for-of loop returns an array of [key, value] for each iteration
  • Pure JavaScript objects are like Maps in that both let you:

Assign values to keys Detect whether something is stored in a key Delete keys image image image image image

What is a Set?

  • Store unique values of any type, whether primitive values or object references
  • Set objects are collections of values image
  • Can iterate through the elements of a set in insertion order

WeakMap and WeakSet

  • Special variants of Map and Set
  • Their elements do not count as active references

Reference types visible (in scope) in the program stack are active Active references remain in memory Out-of-scope references are removed by the garbage collector

  • These collections are used in memory-intensive applications

Clone this wiki locally