Advanced JavaScript or Object-Oriented JavaScript.
Working with JavaScript Objects
Objects
In JavaScript, an object is a standalone entity, and is a container for named values called properties or methods. In real life, a car is an object. A car has properties like make, colour, and style, and methods like start and stop.
Object Properties
Similarly, a JavaScript object has properties associated with it. We can define the object 'car' as follows:
var car = {Make:"Ferrari", "Colour:Red", "Style:Sport"}
The name:value pairs in JavaScript objects are called properties.
Object Methods
A method is a function stored as a property. Methods are actions that can be performed on objects. Methods are stored in properties as function definitions.
var person = {firstName:"John", lastName:"Smith", fullName : function() { return this.firstName + " " + this.lastName; } }
In the example above, 'this' is the person object that "owns" the fullName function, so it follows that, this.firstName means the firstName property of this object.
You access an object method with the following syntax: objectName.methodName() for example, alert(person.fullName()); will return
The Fundamental Concepts - Encapsulation, Abstraction, Inheritance and Polymorphism
Encapsulation describes the idea of bundling data and methods that work on that data within one unit, say, a class. It wraps the data and code that operates on the data (methods) into a single entity, preventing direct (unauthorized) access to that entity. Data can only be accessed by public methods configured to access bundled (say, getter and setter) methods thus making the private fields and their implementation hidden for outside classes.
The Reason for Encapsulation:
• It improves maintainability and flexibility and re-usability • Class variables can be made read-only (if you omit the set method), or write-only (if you omit the get method) • The programmer can change one part of the code without affecting other parts • Increased security of data
• Variables and their implementation is hidden for outside classes.
<script src="prism.js">
function Encapsulation1()
{
class Student // Class Expression
{
constructor()
{
var name; // member variable 1
var marks; // member variable 2
}
getName() // getter method 1
{
return this.name;
}
setName(name) // setter method 1
{
this.name=name;
}
getMarks() // getter method 2
{
return this.marks;
}
setMarks(marks) // setter method 2
{
this.marks=marks;
}
}
var stud=new Student();
stud.setName("John");
stud.setMarks(80);
alert("Excapsulation example 1: Student " + stud.getName()+" achieved "+stud.getMarks() + " marks");
var stud=new Student();
stud.setName("David");
stud.setMarks(76);
alert("Encapsulation example 2: Student " + stud.getName()+" achieved "+stud.getMarks() + " marks");
}
function Encapsulation2(){
function vehicle(thewheels, thecolour){ // object constructor function (class definition) for vehicle
var colour=thecolour;
var wheels=validWheels(thewheels);
function validWheels(wheelsin){
return wheelsin > 4 ? 8 : wheelsin;
}
return {
get colour() {
return colour;
},
set colour(value) {
colour = value;
},
get wheels() {
return wheels;
},
set wheels(value) {
wheels = validWheels(value);
}
}
}
var v1 = new vehicle(40, "red"); //setting new values during instantiation
var v2 = new vehicle(2, "blue");
showVehDetails(v1,1);
showVehDetails(v2,2);
v2.wheels=4; //validated input restricted to 4
showVehDetails(v2,3);
v2.colour="orange";
showVehDetails(v2,4);
}
function showVehDetails(v,i){
alert("Encasulation 2 example " + i + " - This vehicle is " + v.colour + " and has " + v.wheels + " wheels.");
}
</script>
Abstraction means to perceive an entity in a system or context from a particular perspective. We remove unnecessary details and only focus on aspects that are necessary to that context or system under consideration.
The Reason for Abstraction:
• To achieve security by hiding certain details • It's easier to maintain, read and work on the code • It helps to deal with a complex system by concentrating on the essential features only
JavaScript doesn't have the abstract class and interface features normally directly used in abstraction. However, abstract classes with interfaces are implemented indirectly by JavaScript Object.create methods and prototypes. Abstraction and encapsulation are complementary concepts.
<script src="prism.js">
//Abstract Class
function Abstraction()
{
var Gig = function()
{if (this.constructer === Gig) {
throw new Error(" Can't instantiate abstract class!");
}
}
//Corporate Musician Applications: Musician function specification - extends Abstract Class Gig
Gig.prototype.display=function()
{ return "The musician "+this.gigName; }
Musician.prototype=Object.create(Gig.prototype); //Interface
function Musician(gigName)
{ this.gigName=gigName; }
function showResult()
{alert("Abstraction example 1: " +musician.display());}
var musician=new Musician("headlining is Bob Dylan");
showResult();
var musician=new Musician("supporting is Phoebe Bridger");
showResult();
//Corporate Venue Applications: Venue function specification - extends Abstract Class Gig
var Venue = function() {
Gig.apply(this, arguments); };
Venue.prototype = Object.create(Gig.prototype); //Interface
Venue.prototype.say = function() {
alert('Abstraction example 2: The Venue is Wembly Arena'); }
var venue = new Venue();
venue.say();
//Corporate Calendar Applications: Calendar function specification - extends Abstract Class Gig
Gig.prototype.datex=function()
{ return "The gig is from "+this.gigDate; }
Dates.prototype=Object.create(Gig.prototype); //Interface
function Dates(gigDate)
{ this.gigDate=gigDate; }
function dateResult()
{alert("Abstraction example 3: " +calendar.datex());}
var calendar=new Dates("18/10/2019 to 21/10/2019");
dateResult();
}
</script>
Inheritance Inheritance allows programmers to create classes that are built upon existing classes and this makes it possible for a class to inherit attributes and methods of the parent class. JavaScript does not have classes like other languages. It uses the concept of prototypes for inheritance. For inheritance to work, the objects need to have characteristics in common with each other.
The Reason for Inheritance
• It makes a specific section of a project's code reusable.
• It can apply the same class and methods to different data types.
• It makes global changes to derived classes by changing a base class.
Inheritance is most appropriate when the hierarchy represents an 'is-a' (Robert is a name) relationship and not a 'has-a' (the house has a room) relationship and, the class hierarchy continues to be reasonably shallow.
<script src="prism.js">
function(Inheritance);
//Parent - SuperType constructor function
function SuperType(){
this.name = "Robert Brown"
this.nationality = "English"
}
//Add 2 new properties to SuperType prototype
SuperType.prototype.getSuperName = function(){
return this.name // Robert is a name
}
SuperType.prototype.getSuperNationality = function(){ // English is a nationality
return this.nationality
}
//Inheritance => SubType inherits name, getSuperName and getSuperNationality*/
//Child - SubType.prototype = new SuperType();
//SubType prototype function
function SubType(){
this.age = 26
}
//Add new property to SubType prototype
SubType.prototype.getSubAge = function(){
return this.age;
}
var subTypeObj = new SubType();
alert("Inheritance example 1 (with attributes)\r\n" + subTypeObj.name + "\r\nAge is " + subTypeObj.age);
alert("Inheritance example 2 (with methods)\r\n" + subTypeObj.getSuperName() + "\r\nNationality is " + subTypeObj.getSuperNationality() +" \r\nand Age is " + subTypeObj.getSubAge());
</script>
Polymorphism Polymorphism is an object-oriented programming concept that refers to the ability of a variable, function or object to take on multiple forms. A language that features polymorphism allows developers to program in the general rather than program in the specific. Requirements are such that, there must be properties with the same name and the same parameter sets in all the superclasses, subclasses and interfaces.
The Reason for Polymorphism
• It enables objects belonging to different types to respond to methods, fields, or property calls of the same name, each one according to an appropriate type-specific behaviour.
Say there is a base class named Animals from which the subclasses Horse, Fish and Bird are derived. Also assume that the Animals class has a function named Move, which is inherited by all subclasses mentioned. With polymorphism, each subclass may have its own way of implementing the function. So, when the Move function is called in an object of the Horse class, the function might respond by displaying trotting on the screen. On the other hand, when the same function is called in an object of the Fish class, swimming might be displayed on the screen. In the case of a Bird object, it may be flying.
<script src="prism.js">
class Employee{
constructor(name, age){
this.name = name;
this.age = 29;
}
EmployeeName(){
alert(`Polymorphism example: Employee Name ${this.name} and age ${this.age}`);
}
}
class Member extends Employee{
constructor(name, salary, age){
super(name);
this.name = name;
this.salary = salary;
// this.age = age; // Note alert age is 29. If comment removed the second class method will override the parent class method (age = 34).
}
EmployeeName(){
alert(`Polymorphism example: Employee Name ${this.name} and salary ${this.salary} and age ${this.age}`);
}
}
const mbr = new Member("Graham Davies", 39500, 34);
mbr.EmployeeName();
</script>
Resource Management
Computer programs may manage their own resources by using inherent features of programming languages or may elect to manage them by an operating system, virtual machine or another program.
Resource management, is sometimes referred to as resource tracking, and consists of cleaning up resource leaks: terminating access to resources that have been acquired but not released after use. This is known as reclaiming resources and is analogous attempts to reclaim occupied objects that are no longer being used. On many systems the operating system reclaims resources after the process makes the exit system call.
The act of refusing to release a resource when a process has finished using it is known as a resource leak and is an issue in sequential computing (executing a single sequence of instructions). Multiple processes wish to access a limited resource can be an issue in concurrent computing, and is known as resource contention.
Resource management seeks to control access in order to prevent both of these situations.