JavaScript Classes - Inheritance-For Loop
JavaScript Classes - Inheritance-For Loop
In this tutorial, you will learn about JavaScript classes with the help of
examples.
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.
// 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
// 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}`);
}
}
// 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.
class Person {
constructor(name) {
this.name = name;
}
// getter
get personName() {
return this.name;
}
// setter
set personName(x) {
this.name = x;
}
}
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;
}
}
'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;
}
}
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.
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}`);
}
}
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.
// parent class
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`);
}
}
constructor(name) {
// call the super class constructor and pass in the name parameter
super(name);
}
// parent class
class Person {
constructor(name) {
this.name = name;
this.occupation = "unemployed";
}
greet() {
console.log(`Hello ${this.name}.`);
}
constructor(name) {
// call the super class constructor and pass in the name parameter
super(name);
Output
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.
• Since you can also add your own functionalities in the child class,
you can inherit only the useful functionalities and define other
required features.
Here,
// using for...of
for ( let element of students ) {
// display the values
console.log(element);
}
Run Code
Output
John
Sara
Jack
Output
c
o
d
e
Output
1
2
3
// inserting elements
map.set('name', 'Jack');
map.set('age', '27');
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 };
}
}
}
}
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;
}
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.
Here,
let student1 = {
age: 24,
name: "Felix"
}
const handler = {
get: function(obj, prop) {
return obj[prop] ? obj[prop] : 'property does not exist';
}
}
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 = { };
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 = {
return obj[prop];
}
}
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);
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 = {
// check condition
if (prop == 'name') {
return obj[prop];
} else {
return 'Not allowed';
}
}
}
Here, only the name property of the student object is accessible. Else, it
returns Not allowed .
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]) {
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 handler = {
set: function (target, prop, value) {
if (prop === 'name' && value === 'Jack') {
// calling another function
myFunction();
}
else {
console.log('Can only access name property');
}
}
};
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);
setTimeout(greet, 3000);
console.log('This message is shown first');
Run Code
Output
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');
}
Output
Id: 3
Hello world
console.log(time)
Output
5:45:39 PM
5:45:43 PM
5:45:47 PM
5:45:50 PM
..................
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);
let count = 0;
// function creation
function increaseCount(){
// 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:
Output
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.