Object Oriented Javascript
What do you get at the end of this page?
- What is a paradigm?
- What are different types of paradigms?
- Why do we need paradigm?
- What is OOP?
- Some of the OOP supported languages
- How do we achieve OOP in JavaScript. Please explain with examples?
What is a paradigm?
- A programming paradigm is the way of thinking about or approaching problems.
- A programming paradigm is a fundamental style of building the structure and elements of a program.
- It influences the programming language and other things built on top of the language, such as libraries, frameworks, and common styles and patterns of programming.
- The styles and capabilities of programming languages are defined by their paradigms.
What are different types of paradigms?
- Imperative
- Paradigm of computer programming in which the program describes a sequence of steps that change the state of the computer. It explicitly tells the computer "how" to accomplish it not "what" to accomplish
- Declarative
- which describes "what" a program should accomplish not "how" to.
- Object-oriented
- OOP is a programming paradigm based upon objects (having both data and methods) that aims to incorporate the advantages of modularity and reusability. Objects, which are usually instances of classes, are used to interact with one another to design applications and computer programs.
- Functional
- A style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.
- Logic
- (Rule-based): Programming by specifying a set of facts and rules. An engine infers the answers to questions.
- Symbolic
- Structured
- Programming with clean, goto-free, nested control structures.
- Procedural
- Programming by manipulating the program elements themselves.
- Event-driven
- Programming with emitters and listeners of asynchronous actions.
- Flow-driven
- Programming processes communicating with each other over predefined channels.
- Constraint
- Programming by specifying a set of constraints. An engine finds the values that meet the constraints.
- Aspect oriented
- Programming cross-cutting concerns applied transparently.
- Reflected
- Programming by manipulating the program elements themselves.
Why do we need paradigm?
Programming language paradigms are just like genre of music. People like different kinds of music according to their favor, and likely, different problem you are solving should be coded in different paradigms.
For example, you are programming to get the result of "1+1", you should program in Procedural Programming paradigm rather than Object-Oriented paradigm, while OOP could be better than Procedural paradigm in other problems.
Doing everything the same way isn't very productive. There's an old saying that, "when all you have is a hammer, everything starts to look like a nail." I'm guessing you don't want to be the guy who whacks everything with a hammer.
Different models, different approaches, better solutions. It's as simple as that.
Different models, different approaches, better solutions. It's as simple as that.
What is OOP?
OOP is a programming paradigm based upon objects (having both data and methods) that aims to incorporate the advantages of modularity and reusability. Objects, which are usually instances of classes, are used to interact with one another to design applications and computer programs.
Some of the OOP supported languages
- JavaScript
- C#
- C++
- Java
- Ruby
- Python
- PHP etc.,
How do we achieve OOP in JavaScript. Please explain with examples?
There are certain features or mechanisms which makes a Language Object Oriented like:- Object
- Classes
- Inheritance
- Encapsulation
- Data Abstraction(hiding of data)
- Polymorphism
Object:
An Object is a unique entity which contains properties and methods.
We can create object as below:
Object literal(Method-1):
var car = {
"type": "someType",
"model": "someModel",
"color": "Pink",
"horsePower": "Y",
"canDrive": function() {
return "We can drive this "+ this.color+" car of model "+this.model;
}
}
car.canDrive();//"We can drive this Pinkcar of model someModel"
Object constructor(Method-2):
Classes are blueprint of an Object.A class can have many Object, because class is a template while Object are instances of the class or the concrete implementation.
Before we move further into implementation, we should know unlike other Object Oriented Language their is no classes in JavaScript we have only Object. To be more precise, JavaScript is a prototype based object oriented language, which means it doesn’t have classes rather it define behaviors using constructor function and then reuse it using prototype.
Note :- Even the classes provided by ECMA2015 are objects.
Inheritance:
It is a concept in which some property and methods of an Object is being used by another Object. Unlike most of the OOP languages where classes inherit classes, JavaScript Object inherits Object i.e. certain features (property and methods)of one object can be reused by other Objects.
The process of wrapping property and function within a single unit is known as encapsulation.
Let’s understand encapsulation with an example.
function Car(type, model, color) {
this.type = type;
this.model = model;
this.color = color;
}
Car.prototype.canDrive = function(){
return "We can drive this "+ this.color+" car of model "+this.model;
}
var car = new Car("someType", "someModel", "Pink")
car.canDrive();//"We can drive this Pinkcar of model someModel"
With new keyword(Method-3):var myCar = new Object();
myCar.make = 'Ford';
myCar.model = 'Mustang';
myCar.year = 1969;
Classes:Classes are blueprint of an Object.A class can have many Object, because class is a template while Object are instances of the class or the concrete implementation.
Before we move further into implementation, we should know unlike other Object Oriented Language their is no classes in JavaScript we have only Object. To be more precise, JavaScript is a prototype based object oriented language, which means it doesn’t have classes rather it define behaviors using constructor function and then reuse it using prototype.
Note :- Even the classes provided by ECMA2015 are objects.
JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.
ES5:
// Defining class in a Traditional Way.
function Person(name, age) {
this.name = name;
this.age = age;
this.getName = function() {
console.log("Name: "+this.name);
}
}
Person.prototype.getDetails = function() {
console.log("Getting Details from Person: "+this.name, this.age);
return this.name +" "+ this.age;
}
var person = new Person("Divya", "20+");
console.log(person);
console.log(person.getDetails());
ES6:
//Define class using ES6
class Person {
//Defininig the constructor to initialize the property
constructor(name, age) {
this.name = name;
this.age = age;
this.getName = function() {
console.log("Name: "+this.name);
}
}
getDetails() {
console.log("Getting Details from Person: "+this.name, this.age);
return this.name +" "+ this.age;
}
}
//Creating person object
var person = new Person("Divya", "20+");
console.log(person);
console.log(person.getDetails());
Inheritance:
It is a concept in which some property and methods of an Object is being used by another Object. Unlike most of the OOP languages where classes inherit classes, JavaScript Object inherits Object i.e. certain features (property and methods)of one object can be reused by other Objects.
ES5:
// Defining class in a Traditional Way.
function Person(name, age) {
this.name = name;
this.age = age;
this.getName = function() {
console.log("Name: "+this.name);
}
}
Person.prototype.getDetails = function() {
console.log("Getting Details from Person: "+this.name, this.age);
return this.name +" "+ this.age;
}
function Employee(name, age, salary) {
//To inherit instance properties of super
Person.call(this, name, age);
this.salary = salary;
this.getSalary = function() {
console.log("Salary: "+this.salary);
}
}
//Note: New methods must be added to the SubType after the inheritance because inheritance overwrites the existing prototype of SubType
// If we have sup_prototype before sub_prototype, then we would get the getDetails() from Employee(sub_type) otherwise from Person(sup_type)
//We call this Method over riding
//Refer to this block as sup_prototype
Employee.prototype = Object.create(Person.prototype);
//Refer to this block as sub_prototype
Employee.prototype.getDetails = function() {
console.log("Getting Details from Employee: "+ this.name +" "+this.salary+" "+this.age);
return this.name + this.age + this.salary;
}
var person = new Person("Divya", "20+");
console.log(person);
console.log(person.getDetails());
var employee = new Employee("Sai", "15+", 10000000);
console.log(employee);
console.log(employee.getDetails());
ES6:
//Define class using ES6
class Person {
//Defininig the constructor to initialize the property
constructor(name, age) {
this.name = name;
this.age = age;
this.getName = function() {
console.log("Name: "+this.name);
}
}
getDetails() {
console.log("Getting Details from Person: "+this.name, this.age);
return this.name +" "+ this.age;
}
}
class Employee extends Person{
constructor(name, age, salary) {
super(name, age);
this.salary = salary;
this.getSalary = function() {
console.log("Salary: "+this.salary);
}
}
getDetails() {
console.log("Getting Details from Employee: "+ this.name +" "+this.salary+" "+this.age);
return this.name + this.age + this.salary;
}
}
//Creating person object
var person = new Person("Divya", "20+");
console.log(person);
console.log(person.getDetails());
//Creating employee object
var employee = new Employee("Sai", "15+", 10000000);
console.log(employee);
console.log(employee.getDetails());
Encapsulation:The process of wrapping property and function within a single unit is known as encapsulation.
Let’s understand encapsulation with an example.
// Defining class in a Traditional Way.
function Person(name, age) {
this.name = name;
this.age = age;
this.getName = function() {
console.log("Name: "+this.name);
}
}
Person.prototype.getDetails = function() {
console.log("Getting Details from Person: "+this.name, this.age);
return this.name +" "+ this.age;
}
var person = new Person("Divya", "20+");
console.log(person);
console.log(person.getDetails());
In the above example we simply create a person Object using the constructor with some properties and methods.
Some times encapsulation refers to Data abstraction or hiding of data.
Data Abstraction/Hiding of Data:
Means representing essential features hiding the background detail. Most of the OOP languages provide access modifiers to restrict the scope of a variable, but there are no such access modifiers in JavaScript but there are certain ways by which we can restrict the scope of variable within the Class/Object like below.
Along with the below links also refer to my blog
https://www.geeksforgeeks.org/introduction-object-oriented-programming-javascript/
https://www.geeksforgeeks.org/commonly-asked-oop-interview-questions/
https://www.learn-js.org/
// Defining class in a Traditional Way.
function Person(name, age) {//These name, age and getNameNoAccess are
not visible outside the scope of the object
var name = name;
var age = age;
var getNameNoAccess = function() {
console.log("cannotAccessName: "+name);
}
this.getName = function() {
console.log("canAccessName: "+name);
}
}
Person.prototype.getDetails = function() {
console.log("Getting Details from Person: "+this.name, this.age);
return this.name +" "+ this.age;
}
var person = new Person("Divya", "20+");
console.log(person);
console.log(person.getDetails());
console.log(person.getNameNoAccess());//undefined
console.log(person.getName());//it consoles
console.log(person.name);//undefined
Polymorphism:- The ability to call the same method on different objects and have each of them respond in their own way is called polymorphism.
- In OOP, we think of objects that are linked through inheritance has the same methods (override methods) and that the method being called up, is the method associated with the object and not the type of referance.
- This should not be a problem in Java Script as references (variables) in JavaScript is not type-set. We can assign any type of data to a variable in Javascript, and Javascript will know the object a variable refer to if it exists.
- For example, all employees are people, but all people are not employees. Which is to say that people will be the super class, and employee the sub class. People may have ages and weights, but they do not have salaries. Employees are people so they will inherently have an age and weight, but also because they are employees they will have a salary.
function Person(age, weight) {
this.age=age;
this.weight=weight;
this.getInfo=function() {
return "I am " + this.age + " years old " +
"and weighs " + this.weight +" kilo.";
}
}
function Employee(age, weight, salary){
this.salary=salary;
this.age=age;
this.weight=weight;
this.getInfo=function() {
return "I am " + this.age + " years old " +
"and weighs " + this.weight +" kilo " +
"and earns " + this.salary + " dollar.";
}
}
Employee.prototype= new Person();
Employee.prototype.constructor=Employee;
// The argument, 'obj', can be of any kind
// which method, getInfo(), to be executed depend on the object
// that 'obj' refer to.
function showInfo(obj) {
document.write(obj.getInfo()+"<br>");
}
var person = new Person(50,90);
var employee = new Employee(43,80,50000);
showInfo(person);
showInfo(employee)
//I am 50 years old and weighs 90 kilo.<br>
//I am 43 years old and weighs 80 kilo and earns 50000 dollar.<br>
Along with the below links also refer to my blog
https://www.geeksforgeeks.org/introduction-object-oriented-programming-javascript/
https://www.geeksforgeeks.org/commonly-asked-oop-interview-questions/
https://www.learn-js.org/

Comments
Post a Comment