Javascript accommodates what other language might call procedures, subroutines, and functions all in one type of structure: the custom function.
Normally you would create a javascript function in this way:
function shout(arg1, arg2) {
alert(arg1 + arg2);
}
In this way, actually we created an object named ‘shout’. Once function is declared, it is compiled but only run when the function is called. On the other hand, the task of assigning a function name helps you determine the precise scope of activity of the function. If you find that you can’t reduce the planned function name to two to three words, perhaps you are asking the function to do too much things. You may need to break the functions into two.
However, you may not know that you may also create a function in this way:
var shout = function theShout(arg1, arg2) {
alert(arg1 + arg2);
}
In this case, we are assigning a function ‘theShout’ to the variable ‘shout’. As I said just now, by declaring a function, you are creating an object. So now it also makes sense by assigning an object to the variable ‘shout’.
Actually, you don’t even have to name the function at all:
var shout = function (arg1, arg2) {
alert(arg1 + arg2);
}
The difference is that the previous example can refer to the function by the function name or by the assigned variable. This example can only refer to the function by the assigned variable. On the other hand, this technique is also called lambda expression. It provides a shortcut for creating a reference to an anonymous function. The common application of this technique is to assign function references to event handlers.
document.getElementById('name').onClick = function(event) {
alert('You clicked me');
}
The third way of declaring a function is :
var shout = new Function (arg1, arg2, 'alert(arg1 + arg2)')
Javascript is a special kind of Object in javascript. So it means that we could add properties to it.
var Person = function(name) {
this.name = name;//for every instance of the Person object, we add name property to it
}
var person = new Person('Shanison');
person.gender = 'Male'; //add property gender to the person object.
alert(person.name);
alert(person.gender);
Click to run this javascript function
In the above example, we create a function object and use Person variable to refer to this object. So by using new operator, we are creating an instance of the Person object(or rather the object that Person refers to). Then we add the gender property to the person instance. Do note that this gender property is only assigned to the ‘person’ instance of the Person object. So if we create another instance, the gender property won’t be added to it.
var person2 = new Person('Shanison');
alert(person2.gender);
This should give you ‘undefined’ if you run the example.
Click to run this javascript function





