Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
104 views

JavaScript Classes - Inheritance-For Loop

The document discusses JavaScript classes and inheritance. It provides examples of how to define classes, create class methods and properties, extend classes to create child classes, and override methods and properties in child classes. It also discusses the uses of inheritance in JavaScript, including code reusability and adding new functionality while inheriting existing features.

Uploaded by

Pace Infotech
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views

JavaScript Classes - Inheritance-For Loop

The document discusses JavaScript classes and inheritance. It provides examples of how to define classes, create class methods and properties, extend classes to create child classes, and override methods and properties in child classes. It also discusses the uses of inheritance in JavaScript, including code reusability and adding new functionality while inheriting existing features.

Uploaded by

Pace Infotech
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

JavaScript Classes

In this tutorial, you will learn about JavaScript classes with the help of
examples.

Classes are one of the features introduced in the ES6 version of


JavaScript.
A class is a blueprint for the object. You can create an object from the
class.

You can think of the class as a sketch (prototype) of a house. It contains all
the details about the floors, doors, windows, etc. Based on these
descriptions, you build the house. House is the object.

Since many houses can be made from the same description, we can create
many objects from a class.

Creating JavaScript Class


JavaScript class is similar to the Javascript constructor function, and it is
merely a syntactic sugar.
The constructor function is defined as:

// constructor function
function Person () {
this.name = 'John',
this.age = 23
}

// create an object
const person1 = new Person();
Instead of using the function keyword, you use the class keyword for
creating JS classes. For example,

// creating a class
class Person {
constructor(name) {
this.name = name;
}
}

The class keyword is used to create a class. The properties are assigned in
a constructor function.
Now you can create an object. For example,

// creating a class
class Person {
constructor(name) {
this.name = name;
}
}

// creating an object
const person1 = new Person('John');
const person2 = new Person('Jack');

console.log(person1.name); // John
console.log(person2.name); // Jack

Here, person1 and person2 are objects of Person class.

Note: The constructor() method inside a class gets called automatically


each time an object is created.

Javascript Class Methods


While using constructor function, you define methods as:
// constructor function
function Person (name) {

// assigning parameter values to the calling object


this.name = name;

// defining method
this.greet = function () {
return ('Hello' + ' ' + this.name);
}
}

It is easy to define methods in the JavaScript class. You simply give the
name of the method followed by () . For example,

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

// defining method
greet() {
console.log(`Hello ${this.name}`);
}
}

let person1 = new Person('John');

// accessing property
console.log(person1.name); // John

// accessing method
person1.greet(); // Hello John

Note: To access the method of an object, you need to call the method
using its name followed by () .
Getters and Setters
In JavaScript, getter methods get the value of an object and setter methods
set the value of an object.

JavaScript classes may include getters and setters. You use


the get keyword for getter methods and set for setter methods. For
example,

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

// getter
get personName() {
return this.name;
}

// setter
set personName(x) {
this.name = x;
}
}

let person1 = new Person('Jack');


console.log(person1.name); // Jack

// changing the value of name property


person1.personName = 'Sarah';
console.log(person1.name); // Sarah

Hoisting
A class should be defined before using it. Unlike functions and other
JavaScript declarations, the class is not hoisted. For example,
// accessing class
const p = new Person(); // ReferenceError

// defining class
class Person {
constructor(name) {
this.name = name;
}
}

As you can see, accessing a class before defining it throws an error.

'use strict'
Classes always follow 'use-strict'. All the code inside the class is
automatically in strict mode. For example,

class Person {
constructor() {
a = 0;
this.name = a;
}
}

let p = new Person(); // ReferenceError: Can't find variable: a

Note: JavaScript class is a special type of function. And the typeof operator
returns function for a class.
For example,

class Person {}
console.log(typeof Person); // function
JavaScript Class Inheritance
In this tutorial, you will learn about JavaScript class inheritance with the
help of examples.

Class Inheritance
Inheritance enables you to define a class that takes all the functionality
from a parent class and allows you to add more.

Using class inheritance, a class can inherit all the methods and properties
of another class.

Inheritance is a useful feature that allows code reusability.

To use class inheritance, you use the extends keyword. For example,
// parent class
class Person {
constructor(name) {
this.name = name;
}

greet() {
console.log(`Hello ${this.name}`);
}
}

// inheriting parent class


class Student extends Person {

let student1 = new Student('Jack');


student1.greet();
Run Code

Output

Hello Jack
In the above example, the Student class inherits all the methods and
properties of the Person class. Hence, the Student class will now have
the name property and the greet() method.
Then, we accessed the greet() method of Student class by creating
a student1 object.

JavaScript super() keyword


The super keyword used inside a child class denotes its parent class. For
example,

// parent class
class Person {
constructor(name) {
this.name = name;
}

greet() {
console.log(`Hello ${this.name}`);
}
}

// inheriting parent class


class Student extends Person {

constructor(name) {

console.log("Creating student class");

// call the super class constructor and pass in the name parameter
super(name);
}

let student1 = new Student('Jack');


student1.greet();
Here, super inside Student class refers to the Person class. Hence, when the
constructor of Student class is called, it also calls the constructor of
the Person class which assigns a name property to it.

Overriding Method or Property


If a child class has the same method or property name as that of the parent
class, it will use the method and property of the child class. This concept is
called method overriding. For example,

// parent class
class Person {
constructor(name) {
this.name = name;
this.occupation = "unemployed";
}

greet() {
console.log(`Hello ${this.name}.`);
}

// inheriting parent class


class Student extends Person {

constructor(name) {

// call the super class constructor and pass in the name parameter
super(name);

// Overriding an occupation property


this.occupation = 'Student';
}

// overriding Person's method


greet() {
console.log(`Hello student ${this.name}.`);
console.log('occupation: ' + this.occupation);
}
}

let p = new Student('Jack');


p.greet();
Run Code

Output

Hello student Jack.


occupation: Student

Here, the occupation property and the greet() method are present in
parent Person class and the child Student class. Hence, the Student class
overrides the occupation property and the greet() method.

Uses of Inheritance
• Since a child class can inherit all the functionalities of the parent's
class, this allows code reusability.

• Once a functionality is developed, you can simply inherit it. No need


to reinvent the wheel. This allows for cleaner code and easier to
maintain.

• Since you can also add your own functionalities in the child class,
you can inherit only the useful functionalities and define other
required features.

JavaScript for... of Loop


In this tutorial, you will learn about JavaScript for...of loop with the help of
examples.

In JavaScript, there are three ways we can use a for loop.


• JavaScript for loop
• JavaScript for...in loop
• JavaScript for...of loop
The for...of loop was introduced in the later versions of JavaScript ES6.
The for..of loop in JavaScript allows you to iterate over iterable objects
(arrays, sets, maps, strings etc).

JavaScript for...of loop


The syntax of the for...of loop is:

for (element of iterable) {


// body of for...of
}

Here,

• iterable - an iterable object (array, set, strings, etc).


• element - items in the iterable
In plain English, you can read the above code as: for every element in the
iterable, run the body of the loop.

for...of with Arrays


The for..of loop can be used to iterate over an array. For example,
// array
const students = ['John', 'Sara', 'Jack'];

// using for...of
for ( let element of students ) {
// display the values
console.log(element);
}
Run Code

Output

John
Sara
Jack

In the above program, the for...of loop is used to iterate over


the students array object and display all its values.

for...of with Strings


You can use for...of loop to iterate over string values. For example,
// string
const string = 'code';

// using for...of loop


for (let i of string) {
console.log(i);
}
Run Code

Output

c
o
d
e

for...of with Sets


You can iterate through Set elements using the for...of loop. For example,
// define Set
const set = new Set([1, 2, 3]);

// looping through Set


for (let i of set) {
console.log(i);
}
Run Code

Output

1
2
3

for...of with Maps


You can iterate through Map elements using the for...of loop. For example,
// define Map
let map = new Map();

// inserting elements
map.set('name', 'Jack');
map.set('age', '27');

// looping through Map


for (let [key, value] of map) {
console.log(key + '- ' + value);
}
Run Code

Output

name- Jack
age- 27
User Defined Iterators
You can create an iterator manually and use the for...of loop to iterate
through the iterators. For example,
// creating iterable object
const iterableObj = {

// iterator method
[Symbol.iterator]() {
let step = 0;
return {
next() {
step++;
if (step === 1) {
return { value: '1', done: false};
}
else if (step === 2) {
return { value: '2', done: false};
}
else if (step === 3) {
return { value: '3', done: false};
}
return { value: '', done: true };
}
}
}
}

// iterating using for...of


for (const i of iterableObj) {
console.log(i);
}
Run Code

Output

1
2
3
for...of with Generators
Since generators are iterables, you can implement an iterator in an easier
way. Then you can iterate through the generators using the for...of loop.
For example,
// generator function
function* generatorFunc() {

yield 10;
yield 20;
yield 30;
}

const obj = generatorFunc();

// iteration through generator


for (let value of obj) {
console.log(value);
}
Run Code

Output

10
20
30

for...of Vs for...in
for...of for...in

The for...of loop is used to iterate The for...in loop is used to iterate through the keys of an
through the values of an iterable. object.

The for...of loop cannot be used to You can use for...in to iterate over an iterable such arrays
iterate over an object. strings but you should avoid using for...in for iterables.
The for...of loop was introduced in ES6. Some browsers may not support
its use. To learn more, visit JavaScript for...of Support.

JavaScript Proxies
In this tutorial, you will learn about JavaScript proxies with the help of
examples.

In JavaScript, proxies (proxy object) are used to wrap an object and


redefine various operations into the object such as reading, insertion,
validation, etc. Proxy allows you to add custom behavior to an object or a
function.

Creating a Proxy Object


The syntax of proxy is:

new Proxy(target, handler);

Here,

• new Proxy() - the constructor.


• target - the object/function which you want to proxy
• handler - can redefine the custom behavior of the object
For example,

let student1 = {
age: 24,
name: "Felix"
}
const handler = {
get: function(obj, prop) {
return obj[prop] ? obj[prop] : 'property does not exist';
}
}

const proxy = new Proxy(student1, handler);


console.log(proxy.name); // Felix
console.log(proxy.age); // 24
console.log(proxy.class); // property does not exist
Run Code

Here, the get() method is used to access the object's property value. And if
the property is not available in the object, it returns property does not exist .

As you can see, you can use a proxy to create new operations for the
object. A case may arise when you want to check if an object has a
particular key and perform an action based on that key. In such cases,
proxies can be used.

You can also pass an empty handler. When an empty handler is passed,
the proxy behaves as an original object. For example,

let student = {
name: 'Jack',
age: 24
}

const handler = { };

// passing empty handler


const proxy1 = new Proxy(student, {});

console.log(proxy1); // Proxy {name: "Jack", age: 24}


console.log(proxy1.name); // Jack
Run Code

Proxy handlers
Proxy provides two handler methods get() and set() .

get() handler

The get() method is used to access the properties of a target object. For
example,
let student = {
name: 'Jack',
age: 24
}

const handler = {

// get the object key and value


get(obj, prop) {

return obj[prop];
}
}

const proxy = new Proxy(student, handler);


console.log(proxy.name); // Jack
Run Code

Here, the get() method takes the object and the property as its parameters.

set() handler

The set() method is used to set the value of an object. For example,
let student = {
name: 'John'
}

let setNewValue = {
set: function(obj, prop, value) {

obj[prop] = value;
return;
}
};
// setting new proxy
let person = new Proxy(student, setNewValue);

// setting new key/value


person.age = 25;
console.log(person); // Proxy {name: "John", age: 25}
Run Code

Here, a new property age is added to the student object.

Uses of Proxy
1. For Validation

You can use a proxy for validation. You can check the value of a key and
perform an action based on that value.

For example,

let student = {
name: 'Jack',
age: 24
}

const handler = {

// get the object key and value


get(obj, prop) {

// check condition
if (prop == 'name') {
return obj[prop];
} else {
return 'Not allowed';
}
}
}

const proxy = new Proxy(student, handler);


console.log(proxy.name); // Jack
console.log(proxy.age); // Not allowed
Run Code

Here, only the name property of the student object is accessible. Else, it
returns Not allowed .

2. Read Only View of an Object

There may be times when you do not want to let others make changes in
an object. In such cases, you can use a proxy to make an object readable
only. For example,

let student = {
name: 'Jack',
age: 23
}

const handler = {
set: function (obj, prop, value) {
if (obj[prop]) {

// cannot change the student value


console.log('Read only')
}
}
};

const proxy = new Proxy(student, handler);

proxy.name = 'John'; // Read only


proxy.age = 33; // Read only
Run Code

In the above program, one cannot mutate the object in any way.

If one tries to mutate the object in any way, you'll only receive a string
saying Read Only .
3. Side Effects

You can use a proxy to call another function when a condition is met. For
example,

const myFunction = () => {


console.log("execute this function")
};

const handler = {
set: function (target, prop, value) {
if (prop === 'name' && value === 'Jack') {
// calling another function
myFunction();
}
else {
console.log('Can only access name property');
}
}
};

const proxy = new Proxy({}, handler);

proxy.name = 'Jack'; // execute this function


proxy.age = 33; // Can only access name property
Run Code

JavaScript proxy was introduced from the version of JavaScript ES6.


Some browsers may not fully support its use. To learn more,
visit JavaScript proxy.

Javascript setTimeout()
In this tutorial, you will learn about the JavaScript setTimeout() method with
the help of examples.
The setTimeout() method executes a block of code after the specified time.
The method executes the code only once.
The commonly used syntax of JavaScript setTimeout is:

setTimeout(function, milliseconds);

Its parameters are:

• function - a function containing a block of code


• milliseconds - the time after which the function is executed
The setTimeout() method returns an intervalID, which is a positive integer.

Example 1: Display a Text Once After 3 Second


// program to display a text using setTimeout method
function greet() {
console.log('Hello world');
}

setTimeout(greet, 3000);
console.log('This message is shown first');
Run Code

Output

This message is shown first


Hello world

In the above program, the setTimeout() method calls the greet() function
after 3000 milliseconds (3 second).
Hence, the program displays the text Hello world only once after 3 seconds.

Note: The setTimeout() method is useful when you want to execute a block
of once after some time. For example, showing a message to a user after
the specified time.
The setTimeout() method returns the interval id. For example,
// program to display a text using setTimeout method
function greet() {
console.log('Hello world');
}

let intervalId = setTimeout(greet, 3000);


console.log('Id: ' + intervalId);
Run Code

Output

Id: 3
Hello world

Example 2: Display Time Every 3 Second


// program to display time every 3 seconds
function showTime() {

// return new date and time


let dateTime= new Date();

// returns the current local time


let time = dateTime.toLocaleTimeString();

console.log(time)

// display the time after 3 seconds


setTimeout(showTime, 3000);
}

// calling the function


showTime();
Run Code

Output

5:45:39 PM
5:45:43 PM
5:45:47 PM
5:45:50 PM
..................

The above program displays the time every 3 seconds.


The setTimeout() method calls the function only once after the time interval
(here 3 seconds).
However, in the above program, since the function is calling itself, the
program displays the time every 3 seconds.
This program runs indefinitely (until the memory runs out).

Note: If you need to execute a function multiple times, it's better to use
the setInterval() method.

JavaScript clearTimeout()
As you have seen in the above example, the program executes a block of
code after the specified time interval. If you want to stop this function call,
you can use the clearTimeout() method.
The syntax of clearTimeout() method is:

clearTimeout(intervalID);

Here, the intervalID is the return value of the setTimeout() method.

Example 3: Use clearTimeout() Method


// program to stop the setTimeout() method

let count = 0;
// function creation
function increaseCount(){

// increasing the count by 1


count += 1;
console.log(count)
}

let id = setTimeout(increaseCount, 3000);

// clearTimeout
clearTimeout(id);
console.log('setTimeout is stopped.');
Run Code

Output

setTimeout is stopped.

In the above program, the setTimeout() method is used to increase the value
of count after 3 seconds. However, the clearTimeout() method stops the
function call of the setTimeout() method. Hence, the count value is not
increased.

Note: You generally use the clearTimeout() method when you need to cancel
the setTimeout() method call before it happens.

You can also pass additional arguments to the setTimeout() method. The
syntax is:

setTimeout(function, milliseconds, parameter1, ....paramenterN);

When you pass additional parameters to the setTimeout() method, these


parameters ( parameter1 , parameter2 , etc.) will be passed to the
specified function.
For example,

// program to display a name


function greet(name, lastName) {
console.log('Hello' + ' ' + name + ' ' + lastName);
}

// passing argument to setTimeout


setTimeout(greet, 1000, 'John', 'Doe');
Run Code

Output

Hello John Doe

In the above program, two parameters John and Doe are passed to
the setTimeout() method. These two parameters are the arguments that will
be passed to the function (here, greet() function) that is defined inside
the setTimeout() method.

You might also like