Classes & Objects in Java Script

Hey there, I'm Shahima, a humble professional with a penchant for analyzing details and a love for logical reasoning. Currently pursuing my computer engineering major in India, I'm also diving deep into the fascinating realm of data science. Consider Hashnode my personal virtual diary, where I jot down thoughts and discoveries in the coding universe.
Now, here's a little secret: I have a borderline obsession with data structures and algorithms, but let's keep that between us. When it comes to web development, I've got it covered like a perfectly nested div. In fact, I even had the honour of being crowned the victorious champion at the prestigious Smart India Hackathon 2022, where my problem-solving skills were put to the ultimate test. Oh, and did I mention that I miraculously clinched an international rank of 260 in the English Olympiad? Turns out coding and grammar go hand in hand!
As I embark on this exciting journey, I'm on the lookout for opportunities that allow me to unleash my data analysis prowess, decipher intricate patterns, and create models that can predict the future (well, almost). So, if you're seeking a dynamic and driven individual to join your team, consider me your debugging partner. Together, let's revolutionize the world of technology and make it bug-free! Ready to embark on this coding adventure?
In JavaScript, classes are a way to define blueprints for creating objects with similar properties and behaviors. They provide a syntax for creating objects based on a template or prototype. JavaScript classes were introduced in ECMAScript 2015 (ES6) and provide a more structured and familiar approach to object-oriented programming.
Objects In JavaScript:-
Objects can be used to represent complex entities and enable the creation of more advanced data structures in JavaScript. They are a cornerstone of the language and are widely used in web development and other JavaScript applications.
Here are the key properties of objects in JavaScript:
Key-Value Pairs: Objects in JavaScript store data using key-value pairs, where each key is a string (or Symbol) and each value can be any data type.
Object Literals: Objects can be created using object literals, which are enclosed in curly braces
{}. The key-value pairs are defined within the curly braces, separated by commas.Dot Notation: You can access object properties using dot notation, where the object name is followed by a dot (
.) and the property name.For example:
objectName.propertyName.Bracket Notation: Object properties can also be accessed using bracket notation, where the property name is enclosed in square brackets
[].For example:
objectName["propertyName"].Mutability: Objects in JavaScript are mutable, meaning you can add, modify, or delete properties even after the object is created.
Adding Properties: You can add new properties to an object by assigning a value to a new key.
For example:
objectName.newProperty = value.Modifying Properties: Existing properties can be modified by assigning a new value to the corresponding key.
For example:
objectName.propertyName = newValue.Deleting Properties: You can remove properties from an object using the
deletekeyword followed by the object name and the property name.For example:
delete objectName.propertyName.Object Methods: Objects can have methods, which are functions stored as properties of the object. These methods can be accessed and invoked using dot notation.
For example:
objectName.methodName().Object Constructors: Objects can be created using constructor functions or classes, which provide a blueprint for creating multiple instances of objects with similar properties and behaviours.
Object Prototype: Objects in JavaScript inherit properties and methods from a prototype object, which allows for property sharing and method reuse.
Object Serialization: Objects can be converted to a string representation (serialization) using methods like
JSON.stringify(), and can be parsed back into objects usingJSON.parse()
Object creation:-
In JavaScript, objects can be created and manipulated in different ways. Three concepts related to object creation and manipulation are reference types and instantiation.
Reference Types:
In JavaScript, objects are reference types. This means that when you assign an object to a variable or pass it as a function argument, you're actually assigning a reference to the object rather than creating a new copy of it. This reference points to the object's location in memory.
For example:-
let obj1 = { value: 10 };
let obj2 = obj1; // obj2 references the same object as obj1
obj2.value = 20;
console.log(obj1.value); // Output: 20
//also
[]===[] // Output : false
Context and Scope :
Context and scope are related concepts in JavaScript, as they both affect how variables and functions are accessed and behave within a program. While they are distinct concepts, they work together to determine the execution environment and the accessibility of variables and functions.
Here's how context and scope are related:
Scope Determines Variable Accessibility: Scope determines where variables and functions are defined and where they can be accessed within the code. Scopes are created by functions, blocks, and the global scope. The scope chain defines the hierarchy of scopes, allowing inner scopes to access variables and functions defined in outer scopes. So, the scope affects the visibility and availability of variables and functions within a specific context.
Global Scope: Variables and functions declared outside of any function or block have global scope. They are accessible throughout the entire JavaScript program.
Function Scope: Variables and functions declared inside a function are accessible only within that function and any nested functions.
Block Scope: Variables declared with
letandconstkeywords inside a block (e.g., within anifstatement orforloop) is limited to that block's scope and is not accessible outside of it.
Context Determines the Value of "this": The value of the this keyword in JavaScript is determined by the context, which represents the object on which a function is being called. The context determines the execution context for a function and affects how it can access and interact with variables and functions.
Global Context: In the global context (outside any function),
thisrefers to the global object (e.g.,windowin a web browser orglobalin Node.js).Function Context: Within a function,
thisis determined dynamically at runtime, depending on how the function is called. It can refer to different objects based on the context of the function call.Object Method Context: When a function is called as a method of an object,
thisrefers to the object itself. It allows the function to access and operate on the object's properties and methods.
By combining scope and context, you can control the visibility and accessibility of variables and functions within different execution contexts.
Instantiation
Instantiation in JavaScript refers to the process of creating an instance or object based on a blueprint or template. It involves creating a new object that inherits properties and methods from a class or constructor function. There are several distinct fundamental ways to instantiate objects in Javascript:
Constructor Functions:
Constructor functions are traditional functions that are used with the
newkeyword to create objects. They define the structure and behaviour of the objects. Inside the constructor function, properties and methods are assigned tothiskeyword, which refers to the newly created instance.function Player(name, age) { this.nameOfThePlayer = name; this.ageOfThePlayer = age; this.greet = function() { console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`); } } const person = new Person('John', 25); person.greet(); // Output: Hello, my name is John and I'm 25 years old.Classes (new keyword ):
ES6 introduced the class syntax, which provides a more convenient and intuitive way to define objects and their behaviour. Classes act as blueprints for creating objects, and instances are created using the
newkeyword. Classes have constructors that are used to initialize object properties.class player { constructor(name, type) { this.playerName = name; this.playerType = type; } introduce() { console.log(`hi im ${this.playerName} , im a ${this.playerType}`); } } const wizard = new player("shahima", "High priestess"); wizard.introduce(); // Output: hi im shahima , im a High prientessObject Literal Notation:
Object literal notation is a simple and concise way to create objects directly. It involves defining an object using curly braces
{}and specifying the properties and methods within the object declaration.const person = { name: 'John', age: 25, greet: function() { console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`); } }; person.greet(); // Output: Hello, my name is John and I'm 25 years old.Factory Functions: Factory functions are functions that create and return objects. They encapsulate the object creation process and can customize the object's properties and behaviour before returning it.
Object.create():
The
Object.create()method allows you to create a new object with a specified prototype object. It creates a new object and sets the specified object as its prototype, allowing for prototypal inheritance.const personPrototype = { greet: function() { console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`); } }; const person = Object.create(personPrototype); person.name = 'John'; person.age = 25; person.greet(); // Output: Hello, my name is John and I'm 25 years old.
Each of these ways of instantiation has its own syntax and use cases. The choice of which method to use depends on the specific requirements of your code and your coding style preferences.
We will discuss the use of constructors in Class along with inheritance (using ES6 Class Syntax ) for instantiation. This is the latest ES6 method of creating object instances for a class
Inheritance
Inheritance in JavaScript is a mechanism that allows objects to inherit properties and methods from other objects. It provides a way to create a hierarchy of objects where a child object can inherit the characteristics of its parent object.
There are multiple ways to implement inheritance in JavaScript, including:
Prototype Chain Inheritance
Constructor Inheritance
Object.create()
ES6 Class Syntax:
The introduction of ES6 (ECMAScript 2015) introduced a class syntax to JavaScript that simplifies the implementation of inheritance. You can define classes using the
classkeyword, use theextendskeyword to specify the parent class, and utilize thesuperkeyword to call the parent's constructor and access its methods.class ParentClass { constructor() { // parent class constructor } parentMethod() { // parent class method } } class ChildClass extends ParentClass { constructor() { super(); // calling parent class constructor // child class constructor } childMethod() { // child class method } }
Using all of the above concepts
The code demonstrates the use of classes, inheritance, constructors, and method calls in JavaScript. It creates objects of different types (wizard and fighter) that inherit properties and methods from the player class, allowing for specific behaviors and functionality unique to each type of player.
// INSTANTIATION
// involves a number of concepts 1. Constructors 2. inheritence 3.Principal class and derived Class
class player {
constructor(nam, type) {
console.log("player", this);
this.playerName = nam;
this.playerType = type;
}
introduce() {
console.log(`hi im ${this.playerName} , im a ${this.playerType}`);
}
}
// using inheritance
class wizard extends player {
constructor(spell, powers, nam, type) {
// console.log("wiz", this); never use the derived class before "super" it will give error
super(nam, type);
this.spellWiz = spell;
this.powersWiz = powers;
console.log("wiz", this);
}
castSpell() {
console.log(
`I ${this.playerName} posses the power of ${this.powersWiz} , and I now cast a spell ${this.spellWiz}`
);
}
}
class fighter extends player {
constructor(killCapacity, killTime, nam, type) {
super(nam, type);
this.killfig = killCapacity;
this.killtim = killTime;
}
fightBugs() {
console.log(
`I ${this.playerName} posses the kill capacity of ${this.killfig} , and I can kill for ${this.killtim}`
);
}
}
// now instantly creating new players(Objects) of different kinds(wizards and fighters) using main class(player) and derived class(fighters and wizards)
const wiz = new wizard(
"Abra cadabra ",
"Turning readers in coding wizards",
"Shahima",
" HighPriestess"
);
const Bugkiller = new fighter("1000", "0.1 seconds", "Khushi", "cyberQueen");
//
wiz.introduce();
wiz.castSpell();
Bugkiller.introduce();
Bugkiller.fightBugs();
// Out put
// player wizard {}
// wiz wizard {
// playerName: 'Shahima',
// playerType: ' HighPriestess',
// spellWiz: 'Abra cadabra ',
// powersWiz: 'Turning readers in coding wizards'
// }
// player fighter {}
// hi im Shahima , im a HighPriestess
// I Shahima posses the power of Turning readers in coding wizards , and I now cast a spell Abra cadabra
// hi im Khushi , im a cyberQueen
// I Khushi posses the kill capacity of 1000 , and I can kill for 0.1 seconds
Explination:-
Class Definitions:
The
playerclass is defined with a constructor that takesnamandtypeparameters. It initializes theplayerNameandplayerTypeproperties.The
playerclass also has anintroducemethod that logs a message to the console, displaying the player's name and type.The
wizardclass extends theplayerclass using theextendskeyword. It has a constructor that takes additional parametersspell,powers,nam, andtype. It calls the parent class constructor using thesuperkeyword and initializes thespellWizandpowersWizproperties.The
wizardclass also has acastSpellmethod that logs a message to the console, displaying the player's name, powers, and the spell being cast.The
fighterclass also extends theplayerclass. It has a constructor that takes additional parameterskillCapacity,killTime,nam, andtype. It calls the parent class constructor usingsuperand initializes thekillfigandkilltimproperties.The
fighterclass also has afightBugsmethod that logs a message to the console, displaying the player's name, kill capacity, and kill time.
Instantiation:
- Two instances are created:
wizof thewizardclass andBugkillerof thefighterclass. They are initialized with specific values for the constructor parameters.
- Two instances are created:
Method Calls:
The
introduceandcastSpellmethods are called on thewizobject, logging the corresponding messages to the console.The
introduceandfightBugsmethods are called on theBugkillerobject, logging the respective messages to the console.
Output:
The output shows the console logs from the constructors and method calls.
Initially, the constructors of the
wizardandfighterclasses log their respective objects, showing the initial values of the properties.The
introducemethod ofwizdisplays the player's name and type.The
castSpellmethod ofwizdisplays the player's name, powers, and the spell being cast.The
introducemethod ofBugkillerdisplays the player's name and type.The
fightBugsmethod ofBugkillerdisplays the player's name, kill capacity, and kill time.
Entire example at glance






