Object-Oriented JavaScript
By Syncfusion®, Inc. · Last updated
Object properties and methods, accessing, adding, removing and displaying members, constructor functions with new and this, classes with constructors, instance properties and instance methods, and static methods and properties.
What Is Object-Oriented JavaScript?
OOP (object-oriented programming) = organising code into objects that hold data and actions together.
- Member = a named value in an object: a property (data) or a method (a function).
- Class = a plan for making many similar objects.
- Instance = one object made from the plan, with
new.
Simple lesson: write the plan once, then make as many objects from it as you need.
A Real-World Example
A shop has 500 products. Each has a name, a price and a stock count, and each can say its stock value.
One Product class describes all of that once.
new Product("Lunch box", 349) makes one product; the shop makes 500 the same way.
class Product constructor(name, price) stockValue()
new Product("Notebook", 60)
new Product("Lunch box", 349)
new Product("Steel bottle", 299)
One class, many instances, each with its own data.
One box fails on purpose to show the error a class gives without new. Its title says so.
What You Will Learn
- Object properties and methods, and adding, removing and displaying them.
- Constructor functions and
new. - Constructor parameters and
this. - Classes: constructor, instances, instance properties and methods.
- Static methods and static properties.
JavaScript objects
An object groups named values. Think of a library book: details (title, pages) and actions (borrow, return).
Object properties
A property is name: value inside { }. The name is also called a key.
An object with four properties
const book = {
title: "The Hobbit",
author: "J. R. R. Tolkien",
pages: 310,
available: true,
};
console.log(book.title);
console.log(book.pages);
Expected output:
The Hobbit
310
Object methods
A method is a function stored as a property. Inside it, this is the object it belongs to.
A method that uses the object's own properties
const book = {
title: "The Hobbit",
available: true,
borrow() {
this.available = false;
return `You borrowed ${this.title}`;
},
};
console.log(book.borrow());
console.log("Still available?", book.available);
Expected output:
You borrowed The Hobbit
Still available? false
Accessing object members
Dot notation (book.title) most of the time. Brackets (book["page count"]) for spaces or names in variables.
Dot notation and bracket notation reach the same member
const book = { title: "Matilda", author: "Roald Dahl", "page count": 240 };
console.log(book.title);
console.log(book["author"]);
console.log(book["page count"]);
const field = "author";
console.log(book[field]);
Expected output:
Matilda
Roald Dahl
240
Roald Dahl
Adding properties
Assign to a new name, and the property is added. Assign to an existing name, and it changes.
Assigning to a new name adds a property
const book = { title: "Wonder", author: "R. J. Palacio" };
book.pages = 320;
book["genre"] = "Fiction";
console.log(book);
Expected output:
{
"title": "Wonder",
"author": "R. J. Palacio",
"pages": 320,
"genre": "Fiction"
}
const book still lets you change properties. const only stops you from assigning a different object to book.
Removing properties
delete removes a property. in checks whether the name exists.
delete removes a property completely
const book = { title: "Holes", author: "Louis Sachar", shelf: "B4" };
delete book.shelf;
console.log(book);
console.log("Has a shelf?", "shelf" in book);
Expected output:
{
"title": "Holes",
"author": "Louis Sachar"
}
Has a shelf? false
Displaying objects
console.log(obj): the whole object.JSON.stringify(obj): one line of text.`${obj}`: just[object Object]. Use a property instead.- A loop over
Object.entries(obj): your own format.
Four ways to display the same object
const book = { title: "Coraline", author: "Neil Gaiman", pages: 162 };
console.log(book);
console.log(JSON.stringify(book));
console.log(`Template string: ${book}`);
for (const [key, value] of Object.entries(book)) {
console.log(`${key}: ${value}`);
}
Expected output:
{
"title": "Coraline",
"author": "Neil Gaiman",
"pages": 162
}
{"title":"Coraline","author":"Neil Gaiman","pages":162}
Template string: [object Object]
title: Coraline
author: Neil Gaiman
pages: 162
In a browser console, console.table() shows a table (not available in these boxes):
console.table({ title: "Coraline", author: "Neil Gaiman", pages: 162 });
┌─────────┬───────────────┐
│ (index) │ Values │
├─────────┼───────────────┤
│ title │ 'Coraline' │
│ author │ 'Neil Gaiman' │
│ pages │ 162 │
└─────────┴───────────────┘
Object constructors
Writing 100 similar objects by hand is slow and error-prone. A constructor makes them for you.
Constructor functions
A normal function that fills in this, with a capital first letter by convention. No { } object, no return.
A constructor function that builds cars
function Car(make, model) {
this.make = make;
this.model = model;
this.speed = 0;
}
const myCar = new Car("Tata", "Nexon");
console.log(myCar);
Expected output:
{
"make": "Tata",
"model": "Nexon",
"speed": 0
}
Creating objects using new
new makes an empty object, runs the constructor with this set to it, and returns it. Each result is a separate instance.
Each call with new creates a separate object
function Car(make, model) {
this.make = make;
this.model = model;
this.speed = 0;
}
const first = new Car("Tata", "Nexon");
const second = new Car("Honda", "City");
second.speed = 60;
console.log(first.make, first.speed);
console.log(second.make, second.speed);
console.log("Same object?", first === second);
Expected output:
Tata 0
Honda 60
Same object? false
Always use new with a constructor function. Without it, nothing comes back, and the properties leak onto the global object.
Forgetting new: no object comes back
function Car(make, model) {
this.make = make;
this.model = model;
}
const forgotNew = Car("Tata", "Nexon");
console.log("What came back:", forgotNew);
console.log("Where make ended up:", globalThis.make);
Expected output:
What came back: undefined
Where make ended up: Tata
Constructor parameters
Parameters give each instance its own data. A default value fills in a missing one.
Parameters, with a default for the colour
function Car(make, model, colour = "white") {
this.make = make;
this.model = model;
this.colour = colour;
}
const taxi = new Car("Maruti", "Dzire", "yellow");
const family = new Car("Hyundai", "Creta");
console.log(taxi.colour);
console.log(family.colour);
Expected output:
yellow
white
The this keyword
- In a constructor called with
new:thisis the new object. - In
object.method():thisis the object before the dot.
this is the object before the dot
function Car(make, model) {
this.make = make;
this.model = model;
this.speed = 0;
this.accelerate = function (amount) {
this.speed += amount;
return `${this.make} ${this.model} is now doing ${this.speed} km/h`;
};
}
const nexon = new Car("Tata", "Nexon");
const city = new Car("Honda", "City");
console.log(nexon.accelerate(40));
console.log(city.accelerate(25));
console.log(nexon.accelerate(20));
Expected output:
Tata Nexon is now doing 40 km/h
Honda City is now doing 25 km/h
Tata Nexon is now doing 60 km/h
JavaScript classes
Introduction to classes
A class is a plan (like a house blueprint). You cannot live in the plan, but you can build many houses from it.
Why "class"? It describes a whole class, or category, of things.
Creating classes
class Name { constructor() {...} method() {...} }. Setup and methods sit together in one block.
A small Product class
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
describe() {
return `${this.name} costs $${this.price}`;
}
}
const mug = new Product("Coffee mug", 8.5);
console.log(mug.describe());
Expected output:
Coffee mug costs $8.5
Constructor method
constructor runs once per new, to set up the object. One per class; leave it out and you get an empty one.
The constructor runs once for each new object
class Product {
constructor(name, price) {
console.log(`Setting up ${name}...`);
this.name = name;
this.price = price;
}
}
const mug = new Product("Coffee mug", 8.5);
const lamp = new Product("Desk lamp", 24);
console.log("Created:", mug.name, "and", lamp.name);
Expected output:
Setting up Coffee mug...
Setting up Desk lamp...
Created: Coffee mug and Desk lamp
Creating object instances
new Product(...) makes an instance. instanceof checks which class made it.
Two instances of the same class
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
const mug = new Product("Coffee mug", 8.5);
const lamp = new Product("Desk lamp", 24);
console.log(mug);
console.log("Is lamp a Product?", lamp instanceof Product);
Expected output:
{
"name": "Coffee mug",
"price": 8.5
}
Is lamp a Product? true
A class refuses to run without new, so the silent mistake becomes a clear error:
Calling a class without new throws an error
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
const mug = Product("Coffee mug", 8.5);
Instance properties
Each instance has its own data: set it in the constructor (this.name = ...) or as a class field (quantity = 0;).
Instance properties from the constructor and from a class field
class Product {
quantity = 0;
constructor(name, price) {
this.name = name;
this.price = price;
}
}
const mug = new Product("Coffee mug", 8.5);
const lamp = new Product("Desk lamp", 24);
mug.quantity = 12;
console.log(mug.name, mug.quantity);
console.log(lamp.name, lamp.quantity);
Expected output:
Coffee mug 12
Desk lamp 0
Instance methods
Methods in the class body are stored once and shared; inside each call, this is the instance that called it.
Instance methods read and change the instance's own data
class Product {
quantity = 0;
constructor(name, price) {
this.name = name;
this.price = price;
}
restock(amount) {
this.quantity += amount;
return this.quantity;
}
stockValue() {
return this.quantity * this.price;
}
}
const mug = new Product("Coffee mug", 8.5);
const lamp = new Product("Desk lamp", 24);
mug.restock(10);
lamp.restock(3);
console.log("Mug stock value:", mug.stockValue());
console.log("Lamp stock value:", lamp.stockValue());
console.log("Do they share one method?", mug.stockValue === lamp.stockValue);
Expected output:
Mug stock value: 85
Lamp stock value: 72
Do they share one method? true
The constructor sets up each instance's own data; methods describe what every instance can do.
Static members
Static = belongs to the class itself, not to one instance. Use it through the class name.
Static methods
Work about the class as a whole, like comparing two products or building one from text. Instances cannot call it.
A static method is called on the class, not an instance
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
static cheaper(first, second) {
return first.price <= second.price ? first : second;
}
static fromText(text) {
const [name, price] = text.split(":");
return new Product(name, Number(price));
}
}
const mug = new Product("Coffee mug", 8.5);
const lamp = Product.fromText("Desk lamp:24");
console.log("Cheaper:", Product.cheaper(mug, lamp).name);
console.log("Built from text:", lamp.name, lamp.price);
console.log("Can an instance call it?", typeof mug.cheaper);
Expected output:
Cheaper: Coffee mug
Built from text: Desk lamp 24
Can an instance call it? undefined
Static properties
One shared value for the whole class, like a counter or a currency setting.
A shared counter and a shared setting
class Product {
static count = 0;
static currency = "USD";
constructor(name, price) {
this.name = name;
this.price = price;
Product.count += 1;
}
label() {
return `${this.name}: ${this.price} ${Product.currency}`;
}
}
const mug = new Product("Coffee mug", 8.5);
const lamp = new Product("Desk lamp", 24);
const pen = new Product("Gel pen", 1.25);
console.log("Products created:", Product.count);
console.log(pen.label());
Expected output:
Products created: 3
Gel pen: 1.25 USD
Inside a class, write Product.count, not this.count, for a static member.
Classes on a Web Page
A Product class with an instance method and a static counter. Each button calls sell() on its own instance.
Product objects made from one class
class Product {
static count = 0;
constructor(name, price, stock) {
this.name = name;
this.price = price;
this.stock = stock;
Product.count += 1;
}
sell() {
if (this.stock > 0) this.stock -= 1;
}
label() {
return `${this.name} — ₹${this.price} (${this.stock > 0 ? this.stock + " left" : "sold out"})`;
}
}
const products = [new Product("Notebook", 60, 3), new Product("Lunch box", 349, 1), new Product("Steel bottle", 299, 5)];
const list = document.querySelector("#products");
document.querySelector("#status").textContent = `${Product.count} products made from one class`;
for (const product of products) {
const li = document.createElement("li");
const text = document.createElement("span");
const buy = document.createElement("button");
buy.textContent = "Sell one";
text.textContent = product.label() + " ";
buy.addEventListener("click", () => {
product.sell();
text.textContent = product.label() + " ";
console.log(product.name, "stock:", product.stock);
});
li.append(text, buy);
list.append(li);
}
Easy way to remember: class = cookie cutter, instance = cookie, static = a label on the cutter itself.
TL;DR
- Objects hold properties (data) and methods (actions);
thisis the object before the dot. - Constructor functions need
new; classes throw a clear error without it. constructorruns once per instance; methods are shared.- Class fields like
quantity = 0;give each instance a starting value. staticmembers belong to the class:Product.count,Product.cheaper(a, b).
Try this
In the static properties example, add new Product("Notebook", 3) and change currency to "INR". The count becomes 4, and every label shows INR.
Check Yourself
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
Car("Tata", "Nexon") | new is optional | Always new, or use a class | undefined and stray globals |
Product("Mug", 8) | Classes are functions | Classes need new | cannot be invoked without 'new' |
`${book}` | It prints the object | It prints [object Object] | Unreadable output |
mug.cheaper(...) | Instances have static methods | Call Product.cheaper(...) | is not a function |
price inside a method | Methods see properties directly | Use this.price | undefined or an error |
obj.key = undefined to remove | That deletes it | Use delete | The key stays |
Quick reference
| Syntax | Meaning |
|---|---|
const book = { title: "Holes" }; | create an object with an object literal |
book.title or book["title"] | read a property with dot or bracket notation |
book.pages = 233; | add a new property, or change an existing one |
delete book.pages; | remove a property |
"pages" in book | check whether a property exists |
Object.entries(book) | get every property as a [key, value] pair |
function Car(make) { this.make = make; } | a constructor function |
new Car("Tata") | create an instance from a constructor or a class |
class Product { constructor(name) { this.name = name; } } | a class with a constructor method |
quantity = 0; inside a class | a class field, an instance property with a starting value |
describe() { ... } inside a class | an instance method, shared by every instance |
static count = 0; | a static property, stored on the class |
static compare(a, b) { ... } | a static method, called as ClassName.compare(...) |
mug instanceof Product | check whether an object was made from a class |
Exercises
What to Remember
- Objects bundle data with behaviour.
- Classes are plans; instances are the objects.
- Static members belong to the class.
Next: Core OOP Principles. Encapsulation, inheritance, polymorphism and abstraction.