Object Oriented Java Script Constructor Property Method


Object Oriented Programming (OOP) refers to using self-contained pieces of code to develop applications. We call these self-contained pieces of code objects, better known as Classes in most OOP programming languages and Functions in JavaScript. We use objects as building blocks for our applications. Building applications with objects allows us to adopt some valuable techniques, namely, Inheritance (objects can inherit features from other objects), Polymorphism (objects can share the same interface—how they are accessed and used—while their underlying implementation of the interface may differ), and Encapsulation (each object is responsible for specific tasks).

  • Property
  • Method
  • Constructor
  • Inheritance
  • Encapsulation



  

Object Literals
In this case you don't need to (and cannot) create an instance of the class, it already exists. So you simply start using this instance.
apple.color = "reddish";
alert(apple.getInfo());


Object Constructor
An object constructor is merely a regular JavaScript function .
The difference between the two is that a constructor function is called via the new operator.
Lets use a real world item "car" as an example. A property of a car may be its color or name. A method may be to “speed".
The important thing to realize, however is that every car will have a different name.
To create an object type that accommodates this need for flexibility, we'll use an object constructor:

The constructor is called at the moment of instantiation (the moment when the object instance is created).
The constructor is a method of the class.
In JavaScript the function serves as the constructor of the object, therefore there is no need to explicitly define a constructor method.
Every action declared in the class gets executed at the time of instantiation.
Example :
var Person = function () {
  console.log('instance created');
};
var person1 = new Person();
var person2 = new Person();

Example:
function car(name) {
    this.name = name;
    this.speed = function() {
        alert( this.name + " Wow speed!" )
    }
}
car1 = new car(“Maruti")
car1.speed() //
Here the function "car()" is an object constructor, and its properties and methods are declared inside it by prefixing them with the keyword "this." Objects defined using an object constructor are then instantiated using the new keyword. Constructors create the blueprints for objects, not the object itself.


Adding methods to our object using prototype

Prototype is a type of inheritance in JavaScript. We use it when we would like an object to inherit a method after it has been defined. Think of prototyping mentally as "attaching" a method to an object after it's been defined, in which all object instances then instantly share.
 car.prototype.changeName = function(name) {
    this.name = name;
}

firstCar = new car(“Alto")
firstCar.changeName(“Zen")






Constructor
A constructor is any function which is used as a constructor. The language doesn’t make a distinction. A function can be written to be used as a constructor or to be called as a normal function, or to be used either way.
A constructor is used with the new keyword:
var Vehicle = function Vehicle() {
  // ...
}

var vehicle = new Vehicle();

Objects and properties
A JavaScript object has properties associated with it. A property of an object can be explained as a variable that is attached to the object. Object properties are basically the same as ordinary JavaScript variables, except for the attachment to objects. The properties of an object define the characteristics of the object. You access the properties of an object with a simple dot-notation
         objectName.propertyName

u  Like all JavaScript variables, both the object name (which could be a normal variable) and property name are case sensitive. You can define a property by assigning it a value. For example,
let's create an object named myCar and give it properties named make, model, and year as follows:
var myCar = new Object();
myCar.make = “Maruti";
myCar.model = “Alto 800";
myCar.year = 2016;
u  Unassigned properties of an object are undefined.
myCar.noProperty; // undefined



Inheritance
Ø  JavaScript uses a different approach than C# or C++ to create an object-oriented language.
Ø  It is a prototype-based language.
Ø  The concept of prototyping implies that behavior can be reused by cloning existing objects that serve as prototypes. Every object in JavaScript decends from a prototype which defines a set of functions and members that the object can use.
Ø  There is no class. Just objects. Every object can then be used as a prototype for another object.

Example
 var Branch = function() {
    this.name = "IT";
}
       
        Branch.prototype.display=function(){
             document.write(this.name+'<br>');
           
            //this.model="Alto-800";
            //return model;
        }

// This is exactly where the magic happens! By cloning the prototype, we transfer all members and functions to the new class.
        
        var inheritsFrom = function (child, parent) {
    child.prototype = Object.create(parent.prototype);
};
var Student = function() {
           
    this.name = "Sharjeel";
            this.lname = "Bilali";
           
   
}

Branch.prototype.display=function(){
             document.write(this.name+'<br>');
           
            //this.model="Alto-800";
            //return model;
        }
inheritsFrom(Student, Branch);
// We can even override the print function for ClassB:
        //call function we can call the base function on the current object (this).
       
        Student.prototype.display = function() {
    Branch.prototype.display.call(this);
    document.write(this.lname+'<br>');
}
var Faculty = function () {
           
    this.name = "Affan";
            this.lname = "Biz";
   
}
    inheritsFrom(Faculty, Student);

Faculty.prototype.display = function () {
    Student.prototype.display.call(this);
    document.write("Object Oriented Javascript!");
}
       var facl = new Faculty();
facl.display();







Encapsulation

Encapsulation refers to enclosing all the functionalities of an object within that object so that the object’s internal workings (its methods and properties) are hidden from the rest of the application.
One of the main principles with OOP is encapsulation: put all the inner workings of an object inside that object. To implement encapsulation in JavaScript, we have to define the core methods and properties on that object.
To do this, we will use the best pattern for encapsulation in JavaScript: the Combination Constructor/Prototype Pattern.

Implementation of Combination Constructor/Prototype Pattern
Example: 
 function User (theName, theEmail) {
    this.name = theName;
    this.email = theEmail;
    this.quizScores = [];
    this.currentScore = 0;
}          

Implementation of Combination Constructor/Prototype Pattern
The Above lines initialize the instance properties. These properties will be defined on each User instance that is created.
So the values will be different for each user.
The use of the this keyword inside the function specifies that these properties will be unique to every instance of the User object:

User.prototype = {
    constructor: User,
    saveScore:function (theScoreToAdd)  {
        this.quizScores.push(theScoreToAdd)
    },
    showNameAndScores:function ()  {
        var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
        return this.name + " Scores: " + scores;
    },
    changeEmail:function (newEmail)  {
        this.email = newEmail;
        return "New Email Saved: " + this.email;
    }
}

In the code above, we are overwriting the prototype property with an object literal, and we define all of our methods (that will be inherited by all the User instances) in this object.

Make Instance of the User Function
// A User ​
firstUser = new User(“Sharjeel", “Sharjeel.bilali@example.com");
firstUser.changeEmail(“Sharjeel.bilali @edynamic.net");
firstUser.saveScore(15);
firstUser.saveScore(10);
firstUser.showNameAndScores(); //Sharjeel Scores: 15,10​
​// Another User​
secondUser = new User(“Affan", “Affan@example.com");
secondUser.saveScore(18);
secondUser.showNameAndScores(); //Affan Scores: 18


Public and Private Method

Actually in JavaScript functions can be also objects.
Any variable defined with the “var” keyword becomes private, because it’s only visible inside the function body,
while by using the “this” keyword we can define global variables visible outside the function body.
 var f = function()
{
            var a = 10;
             this.b= 5;
}

var myfunc = new f();
console.log(myfunc.a); // is undefined because a is private
console.log(myfunc.b); // equals to 5 because b is public


  
Polymorphism

The ability to call the same method on different objects and have each of them respond in their own way is called polymorphism.
Polymorphism is the main pillar of Object Oriented Programming, it refers to the ability of an object to provide different behaviors in different state of objects.
Example
Parent class Human define a function of introduction() in which it contains simple introduction but Student object override it by adding more detailed information for introduction. So now Human() object has its own implementation of introduction and Student() has its own. It will be invoked according to the state of object.

//Define human class
function Human(fullName) {
  this.fullName = fullName;
}
// Add a couple of methods to Human.prototype
Human.prototype.speak = function(){
  alert("I speak English!");
};
Human.prototype.introduction = function(){
  alert("Hi, I am " + this.fullName);
};

//Define Student class
function Student(fullName, school, courses) {
  Human.call(this, fullName);
  // Initialize our Student properties
   this.school = school;
   this.courses = courses;
};
Student.prototype = Object.create(Human.prototype); // See note below
// Set the "constructor" property to refer to Student
Student.prototype.constructor = Student;

// override the "introduction" method
Student.prototype.introduction= function(){
  alert("Hi, I am " + this.fullName + ". I am a student of " + this.school + ", I study "+ this.courses +".");
};
// Add a "exams" method
Student.prototype.takeExams = function(){
  alert("This is my exams time!");
};

var student = new Student("Ahmed","NED University", "Computer Science");
student.introduction();   // "Hi, I am Ahmed. I am a student of NED University, I study Computer Science."
student.speak();       // "I speak English!"
student.takeExams(); // "This is my exams time!"
// Check that instanceof works correctly
alert(student instanceof Human);  // true
alert(student instanceof Student); // true




Comments

Popular posts from this blog

Error : DependencyManagement.dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: com.adobe.aem:uber-jar:jar:apis -> version 6.3.0 vs 6.4.0

Operators in Asterisk with Linux

ERROR Exception while handling event Sitecore.Eventing.Remote.PublishEndRemoteEventException: System.AggregateExceptionMessage: One or more exceptions occurred while processing the subscribers to the 'publish:end:remote'