ES6 classes concepts

Classes  : is a  blueprints for objects .
  • Using Class, we reuse logic i.e creating multiple similar objects.               


Objects in JavaScript may be defined as an unordered collection of related data, of primitive or reference types, in the form of “key: value” pairs. These keys can be variables or functions and are called properties and methods, respectively, in the context of an object.



Class field Vs properties :

  • field is a variable that is declared directly in a class or struct. ... Properties enable a class to expose a public way of getting and setting values. A get property accessor is used to return the property value, and a set accessor is used to assign a new value.

class product {
category = 'Default' //(public class field)
constructor(title){
this.title = title; //publicclassproperty
}
    
// (public class method)
printinfo(){
console.log(this.title, this.category);

}
}




Defining A ES6 class:
 
class Mobile {

constructor() {

// Instance member
this.model = 'Galaxy'; }
show() { // prototype member
return this.model + "Price 3000";
}
}
const nokia = new Mobile();
console.log(nokia.show);

output :

ƒ show() { // prototype member return this.model + "Price 3000"; }

  • here , it is returing function objects instead of value. This is because we are only passing function name instead of method in console.log(show).

  • Classes are infact a function :" Special functions". In JS, there is not CLasses concepts but the thing is there is only J.S objects .

  • console.log(typeof Mobile); // functions
                     cdb
                       
class Mobile {

constructor() {
this.model = 'Galaxy'; // Instance member
}
show() { // prototype member
return this.model + "Price 3000";
}
}
const nokia = new Mobile();
console.log(nokia.show()); // passing method

output:

GalaxyPrice 3000



  • "Here , Constructor is a special method for creating and initalizing object created within a class
  • There can be only one constructor within a class"

Default Constructor:

  • if, you don't specify constructor method , a default constructor is used.
class Mobile {

model = 'Galaxy'; // Instance member

show() { // prototype member
return this.model + "Price 2000";
}
}
const nokia = new Mobile();
console.log(nokia.show());

  • That , means in above code snippet you were overriding default constructor.





Parameterized Constructor:

class Mobile {
// passing parameter as model_no
constructor(model_no) {
this.model = model_no; // Instance member
}
show() { // prototype member
return this.model + "Price 3000";
}
}
const nokia = new Mobile('Galaxy');
console.log(nokia.show()); // passing method

Output:

GalaxyPrice 2000



Inheritance Concept:

 Inheritance is a mechanism in which one class acquires the property of another class. For example, a child inherits the traits of his/her parents. With inheritance, we can reuse the fields and methods of the existing class. Hence, inheritance facilitates Reusability and is an important concept of OOPs.

Types of Inheritance

There are Various types of inheritance:

Single Inheritance:

In Single Inheritance one class extends another class (one class only).

Types of Inheritance
Single Inheritance

In above diagram, Class B extends only Class A. Class A is a super class and Class B is a Sub-class.

Multiple Inheritance:

In Multiple Inheritance, one class extending more than one class. 

Types of Inheritance
Multiple Inheritance

As per above diagram, Class C extends Class A and Class B both.

Multilevel Inheritance:

In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived class becomes the base class for the new class.

Types of Inheritance
Multilevel Inheritance

As per shown in diagram Class C is subclass of B and B is a of subclass Class A.

Hierarchical Inheritance:

In Hierarchical Inheritance, one class is inherited by many sub classes.

Types of Inheritance
Hierarchical Inheritance

As per above example, Class B, C, and D inherit the same class A.


Class inheritance :

  • The extend Keyword is used in class declarations as a class expressions to create class which is child class of another class.

  • The extends Keyword can be used to subclass custom classes as well as built-in objects like Date, string, Array.

// Baseclass or parent class or super class
class ParentClass {

showFmoney() {
return "FatherMoney";
}
}
// Dervied class / subchild/ child class
class ChildClass extends ParentClass {

showCmoney() {
return "ChildMoney";
}
}

const c = new ChildClass();
console.log(c.showCmoney()); // childMoney
console.log(c.showFmoney()); // Parent Money


Inheritance with constructor in parentClass:

constructor(money) {
this.fmoney = money;
}
showFmoney() {
return this.fmoney;
}
}
// Dervied class / subchild/ child class
class ChildClass extends ParentClass {

showCmoney() {
return "ChildMoney";
}
}

const c = new ChildClass('1000');
console.log(c.showCmoney());
console.log(c.showFmoney());

output :
ChildMoney
1000

Inheritance with super Keyword concept: Constructor in both parent and child  :


// Baseclass or parent class or super class
class ParentClass {
constructor(money) {
this.fmoney = money;
}
showFmoney() {
return this.fmoney;
}
}
// Dervied class / subchild/ child class
class ChildClass extends ParentClass {
constructor() {
this.Cmoney = money
}

showCmoney() {
return this.Cmoney;
}
}

const c = new ChildClass('1000');
console.log(c.showCmoney());
console.log(c.showFmoney());


output:
index.html:33 Uncaught ReferenceError: Must call super constructor in derived
class before accessing 'this' or returning from derived constructor at new ChildClass (index.html:33) at index.html:41 ChildClass @ index.html:33 (anonymous) @ index.html:41



Using super keyword :

  • the problem  is : now we have initalize constructor in both the classes but the fact is we cannot access property of father with class object. so use of super keyword is prime.
  • "it is responsilbiltiy that derived class must be initalized with super class constructor"

// Baseclass or parent class or super class
class ParentClass {
constructor(money) {
this.fmoney = money;
}
showFmoney() {
return this.fmoney;
}
}
// Dervied class / subchild/ child class
class ChildClass extends ParentClass {
constructor(money) {
super(money) // use of super keyword to solve this issues
this.Cmoney = money
}

showCmoney() {
return this.Cmoney;
}
}

const c = new ChildClass('1000');
console.log(c.showCmoney());
console.log(c.showFmoney());

output :

1000
1000


Method overriding: 

  • Same function  name with different implementation
// Baseclass or parent class or super class
class ParentClass {
constructor() {
this.greet = 'hi';
}
showgreet() {
return this.greet;
}
}
// Dervied class / subchild/ child class
class ChildClass extends ParentClass {
constructor() {
super() // use of super keyword to solve
this issues
this.greet = 'hello';
}

showgreet() {
return this.greet;
}
}

const c = new ChildClass();
console.log(c.showgreet());

Output:

hello

IN above code snippet, both child plus parent class have same
methodname show() method , that is overriding behavior
of childclass.

             

Do OverLoading exist in javascript ??

  • Method Overloading is a feature that allows a class to have more than one method having the same name, if their argument lists are different.

Let’s have a look at the following example:


function addNumbers(n1, n2, n3) {
return n1 + n2 + n3;
}

function addNumbers(n1, n2) {
return n1 + n2;
}

var sum = addNumbers(1, 2, 3);

" If overloading worked correctly the value of sum would be 6. However, as JavaScript doesn’t support overloading, the value of sum is something else."

"JavaScript supports overriding not overloading, meaning, that if you define two functions with the same name, the last one defined will override the previously defined version and every time a call will be made to the function, the last defined one will get executed. Looking at the above example, the value of sum will be equal 3 instead of 6."


STATIC Method :

  • is used to define static method for class
  • called without creating object and cannot be called through class instance

class Mobile {
constructor() {}
static display() {
return 'static method'
}
}
        const m = new Mobile() >>> omit this part
        console.log(m.display()) // error >>> omit this part
console.log(Mobile.display()); // Static method

  • With this we can conclude that static method depends only upon class, not the object. 
  • Are often used to create Utiltiy function for an app

"Static methods are generally utility methods or just general purpose methods that don't belong to any instance but instead to a class itself. They take in most inputs through arguments.

For example:
String.valueOf()

This method converts various things to a String object. The method is a static one, meaning that it belongs to the String class itself. You cannot call it as a method of any String object because it doesn't modify or use the properties of an existing String in any way - it only takes an input and returns a new String. "

A (usually) static method. Used when you need to do stuff that does not need an instance of a class.

Example: A math class has an add function. That function needs no state to operate on, only two numbers to add. It doesn't need to touch any of the member / instance variables of the math class, so it's preferable to make it static, rather than member"


Object configuration : property getter and setters

There are two kinds of properties.

  • The first kind is data properties. We already know how to work with them. All properties that we’ve been using until now were data properties.

  • The second type of properties is something new. It’s accessor properties. They are essentially functions that work on getting and setting a value, but look like regular properties to an external code.

SYNTAX:

let obj = {
get propName() {
// getter, the code executed on getting obj.propName
},
set propName(value) {
// setter,
the code executed on setting obj.propName = value
}
};

The getter works when obj.propName is read, the setter – when it is assigned.


let User = {
fname: 'dinesh',
lname: 'Silwal',
get fullname() {
return this.fname + " " + this.lname;
}
}
console.log(User.fullname) // dinesh silwal



  • From outside, an accessor property looks like a regular one. That’s the idea of accessor properties. We don’t call user.fullName as a function, we read it normally: the getter runs behind the scenes.

  • As of now, fullName has only a getter. If we attempt to assign user.fullName=, there will be an error:



let user = {
get fullName() {
return `...`;
}
};

user.fullName = "Test"; // Error (property has only a getter)


  • Let’s fix it by adding a setter for user.fullName:

let user = {
name: "John",
surname: "Smith",

get fullName() {
return `${this.name} ${this.surname}`;
},

set fullName(value) {
[this.name, this.surname] = value.split(" ");

}
};
user.fullName = 'Alice Coper';
console.log(user.fullName); // Alice Coper


















Comments

Popular posts from this blog

JavaScript — Double Equals vs. Triple Equals - weird things on JavaScript

06_Understanding Execution Context and Execution Stack in Javascript

Creating and inserting element- part-2