Java Script functions

In javascript, there are three ways to declare functions.

  1. Named expression

    function f(){
     console.info("I am a named expression");
    }
    f();
  2. Anonymous expression

    var f1 = function(){
     console.info("I am a anonymous expression");
    }
    f1();
  3. Mixing both – hybrid approach

    var f22 = function f2(){
    console.info("m\"ixing both - hybrid approach");
    }
    f22();

Code 

In javascript functions are objects that can be invoked/initialize

//Function as a object

var f3= function(){
 console.info("I am a testing function");
}

f3.greet = "Hello World!";
f3();

console.info(f3.greet);

More Examples

// Object Literal notation

var obj = {
 id:100,
 getId:function(){
 return this.id;
 }
};

console.info(obj.getId())

//Function as an object - Constrcution function

var obj1 = function (fName,lName){ //or var obj1 = function Student(fName,lName){ 
 this.fName = fName;
 this.lName = lName;
 
 this.getFullName = function(){
 return this.fName+' '+this.lName;
 }
}

var std = new obj1('Nuwan','Chathuranga');
console.info(std.getFullName()) 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s