Object Oriented Javascript - 3 : Function

continuing Object Oriented Javascript - 2 : Prototype

Function

Defining a function

A function can be defined in different ways.

#

1. Using keyword function

This is the simplest way to define a function in Javascript and the syntax is same as common function declaration.

function add(a, b){  
 return a+b;  
}

var sum = add(3, 5);

#

2. Using Javascript type Function

A function can also be defined using Javascript type Function

syntax is new Function([params], body);

var add = new Function("a", "b", "return a+b");
var sum = add(3, 5);

Function to create Objects

Function can be used to extend Javascript type Object and can be instantiated.

#

A simple Object

var Car = function (){  
 this.name = "i20";  
 this.brand = "Hyundai";  
}

var car = new Car();  
alert(car.name);  

#

An Object with function

var Car = function (){  
 this.name = "i20";  
 this.brand = "Hyundai";  
 this.showName = function(){  
   alert(this.name);  
 }  
}

var car = new Car();  
car.showName();

Object, Prototype, Function

What makes Javascript powerful is the combination of Object, Prototype and Function. It is the foundation of everything in Javascript, but a bit confusing. Let us work on some exercises and figure it out – Exercise1.

.

Share