JavaScript 

With OOP Concepts


Content



  • JS Data Structures
  • JS Object
  • Functions
  • Prototype
  • Inheritance
  • Overriding

Data Structures

The ECMAScript standard defines six data types:
  • Number
  • String
  • Boolean
  • Null     //   typeof null === 'object'
  • Undefined
  • Object

Object

Object is unordered collection of properties with arbitrary values
It can be an Associative array like JSON or it can even be a function

   var obj = {};

var obj = { name: 'Jason', age: 20 };

var fn = function () { };

Object Cont'd

Adding a property to an object


obj.propertyName = 'this has a value';
OR
obj['propertyName'] = 'this has a value';

Accessing a property of an object

var x = obj.propertyName ;
OR
var x = obj['propertyName'] ;

object cont'd


Creating new objects
  • Using Object Literals
var obj = { name: 'Jason', age: 20 };

  • Using Constructor with new keyword
var car2 = new Car("Nissan", "300ZX", 1992);

  • Using Object.create

Functions

Is an Object
Have methods and properties
Invokable

Properties
  arguments , caller , length  and name
Methods
  apply , bind , call  , isGenerator , toSource , toString

Functions cont'd

Functions can be as..

function myFunction(prop) { 
	return something ;
};
var myFunction = function (prop) { };
var myFunction = function newFn(prop) { }; 

If a return value is not set it will return undefined

Functions cont'd

Arguments
  • The arguments object is a local variable available within all functions
  • Can access and set values by treating it as an Array
  
   function myFunction( prop1, prop2){     var val = arguments[0];    arguments[0] = 'Some Value';
  }; 
  • It is similar to an Array, but does not have any Array properties except length
  • It has 2 other properties callee & caller which has reference to the current function and to the function which invoked the current function

functions cont'd

Constructors

function Phone( model , manufacturer) { 
    this.model = model ;
    this.manufacturer = manufacturer ;
    this.displayModel = function(){
        alert(this.model);
    }
    this.displayManu = function(){
        alert(this.manufacturer);
    }
};

var myXperia = new Phone('Xperia','SONY'); 

Functions cont'd

Constructor property
	 myXperia.constructor === Phone // true        var o = {};	o.constructor === Object; // true
	var a = [];
	a.constructor === Array; // true
 

functions cont'd

SCOPE : Using JS Functions like classes 
As in the Phone example we can use functions with the constructor
  • Declaring private methods and variables using var.
function Phone( ) { 
    var propertyName = 'some value';
    var functionName = function(){ ... };
}; 

  • Declaring public methods and variables using this  this.propertyName = 'some value';
   

functions cont'd

  • Declaring static variables and methods.
    
   Classname.propertyName = 'some value' ;   Phone.color = 'Black' ; 
How to create something like a static class

  

    var staticObj = {     method1 : function (){ alert('method1');} ,    method2 : function (){ alert('method2');}
    }
  staticObj.method2(); 

functions cont'd

  • Way of caching a result using static properties
from john resigs
function isPrime( num ) { 
  if ( isPrime.cache[ num ] != null ) 
    return isPrime.cache[ num ]; 
   
  var prime = num != 1; // Everything but 1 can be prime 
  for ( var i = 2; i < num; i++ ) { 
    if ( num % i == 0 ) { 
      prime = false; 
      break; 
    } 
  } 
  isPrime.cache[ num ] = prime ;
  return prime; 
} 
isPrime.cache = {};
isPrime(5);
 

functions cont'd

  • Context :
  • We can use apply() and call() methods to change the context of another object

  • Function.prototype.call()
Takes arguments separated by commas (‘ , ’)

  • Function.prototype.apply()
Takes arguments as an array

functions cont'd

  • Example :

var numbers = [5, 6, 2, 3, 7];
var max = Math.max.apply(Math, numbers);

var numbers = [5, 6, 2, 3, 7];
var max = Math.max.call(Math, 5,6,3,2,7);

functions cont'd

  • Changing Context :
function Car(){
    this.noWheels = 4; 
}
Car.prototype.color = 'black';
var c = new Car();
function changeColor(color){
    this.color = color;
}
changeColor.call(c,'white');
alert(c.color); 

JS Prototype

  • We can add properties and methods using prototype
  • Saves memory
function Car(){
}
Car.prototype.wheels = 4;

Car.prototype.drive = function (){
    alert('drive');
};
 

prototype cont'd

function Car(){
    this.drive = function(){
        alert('unable to drive right now');
    }
}

Car.prototype.drive = function (){
    alert('drive');
};

var c = new Car();
c.drive(); // what will be the alert ? 

prototype cont'd

hasOwnProperty
function Car(){
    this.noWheels = 4; 
}
Car.prototype.color = 'black';
   var c = new Car();

  c.hasOwnProperty('color');  // false
  c.hasOwnProperty('noWheels');  // true
  c.__proto__.hasOwnProperty('color') // true
 

Inheritance

Prototypal Inheritance
function Person(){}
Person.prototype.dance = function( ){ alert('dancer');  };

function Dancer(){}
Dancer.prototype = new Person();

var dancer = new Dancer();
dancer.dance();
alert(dancer instanceof Dancer); // true
alert(dancer instanceof Person); // true 

inheritance cont'd

  • Some Piece is missing

alert(dancer.constructor === Dancer) // false
alert(dancer.constructor === Person) // true
 
  • We have to reset the Constructor

Dancer.prototype.constructor = Dancer;
alert(dancer.constructor === Dancer) // true 

inheritance cont'd

Example from Mozilla
function Product(name, price) {
  this.name = name;
  this.price = price;

  if (price < 0)
    throw RangeError('Cannot create product "' + name + '" with a negative price');
  return this;
} 

function Food(name, price) {
  Product.call(this, name, price); // call super using call and passing ‘this’ 
  this.category = 'food';
}
Food.prototype = new Product();
var cheese = new Food('feta', 5);
alert(cheese.name); 

inheritance cont'd

Creating a Custom Error using inheritance
function MyError(message) {
  this.name = "MyError";
  this.message = message || "Default Message";
}
MyError.prototype = new Error();
MyError.prototype.constructor = MyError; 

  • However Mozilla says Custom Error Messages will not give the error line correctly

Overriding

function Person(){}
Person.prototype.dance = function( ){ alert('dance');  };

function Dancer(){}
Dancer.prototype = new Person();
Dancer.prototype.dance = function(){ alert('dance better')};
var dancer = new Dancer();
dancer.dance(); // alert dance better 

Reference

http://ejohn.org/apps/learn/
Mozilla.org
bits & pieces from everywhere






Humble try to share Knowledge
Made with Slides.com