1. Function Declaration
This is normal way of declaration using “function” keyword followed by function name and list of parameters
x(5,10) ; // output : 15
x(2,3); // output : 5
This is normal way of declaration using “function” keyword followed by function name and list of parameters
Example:
function Add(a,b)
{
return a+b;
}
Add(5,10) ; // output - 15
Add(2,3); // output – 5
2. Function Expression
var x= function Add(a,b)
{
return a+b;
}
x(5,10) ; // output : 15
x(2,3); // output : 5
3. Function Constructor
var x = new function(“a”,”b”,”return a+b”);
function Add(a,b)
{
return a+b;
}
Add(5,10) ; // output - 15
Add(2,3); // output – 5
2. Function Expression
- It is determined by function keyword followed by list of parameters
- It acts as anonymous function i.e. without function name
- A function expression can be stored in a variable, after that the variable can be used as a function
var x= function Add(a,b)
{
return a+b;
}
x(5,10) ; // output : 15
x(2,3); // output : 5
3. Function Constructor
- It is determined using “new” keyword followed by “function” keyword
var x = new function(“a”,”b”,”return a+b”);
x(5,10) ; // output : 15
x(2,3); // output : 5
4. Invoke Function as object method
var empObj = {
firstName: ” Christopher”
lastName: ” Nolan”
fullName: function() {
return this.firstName + “ “ + this.lastName ;
}
}
empObj.fullName(); // output : Christopher Nolan
5. Invoke Function with a Function Consturctor
function emp(fname,lname)
this.firstName = fname
this.lastName = lname
this.fullName: function() {
return this.firstName + “ “ + this.lastName ;
}
}
var empObj = new emp(“Christopher”,” Nolan”);
empObj.firstName; // output : Christopher
6. Self-Invoking Function
- It allows us to define function as object methods
var empObj = {
firstName: ” Christopher”
lastName: ” Nolan”
fullName: function() {
return this.firstName + “ “ + this.lastName ;
}
}
empObj.fullName(); // output : Christopher Nolan
5. Invoke Function with a Function Consturctor
- If a function invocation is preceded with the new keyword, it is a constructor invocation
function emp(fname,lname)
this.firstName = fname
this.lastName = lname
this.fullName: function() {
return this.firstName + “ “ + this.lastName ;
}
}
var empObj = new emp(“Christopher”,” Nolan”);
empObj.firstName; // output : Christopher
6. Self-Invoking Function
- A self-invoking expression is invoked automatically, without being called.
- b) Function expressions will execute automatically if the expression is followed by ()
( function() {
console.log(“Christopher”);
})();
// output : Christopher
console.log(“Christopher”);
})();
// output : Christopher
Happy Coding :)
No comments:
Post a Comment