Background
Function is the one of the most important thing in JavaScript. Every web developer knows how to write JavaScript Functions. But how much we know about JavaScript Function?
In this series of articles, I'd like to give a summary on how to define and use Functions in JavaScript. It is just a summary, base on already exisiting knowleges, but I believe this would help us writing beautiful JavaScript code, in more reasonable organization and structure.
What is Function?
Function is a piece of code, and is executed when it is called by name.
Function is also a data type in JavaScript, just like other data types such as "Number", "String", "Boolean", "Array" and "Object". This is a difference between JavaScript and other programming language.
Another important thing we should know is: Function data type, as other primary data type ("Number", "String", "Boolean", "Array"), are all "inherited" from Object data type. We will discuss this in later part.
There are a bunch of built-in Functions in JavaScript, for example:
[Type specific Functions]
Array.prototype.concat()
Boolean.prototype.toString()
Number.prototype.toFixed()
Date.prototype.valueOf()
....
[Global Functions]
alert()
prompt()
confirm()
eval()
parseInt()
.......
User can define his/her own Functions, user defined Functions are our main topic.
What is function?
A duplicated headline? Absolutely not.
Notice this "function" is in lower case. "function" in lower case is nothing except a reserved word in JavaScript, which is used to declare a Function, or say a block of code.
How to declare Function?
There are 4 ways to declare Function:
1) Most usual way
function funcName([params]){funcBody};
For example:
function calc(a, b)
{
return a + b;
}
alert(calc(3, 5)); // output 8
When we decalare function in this way, the function body is compiled. Meanwhile, a variable with the same function name (calc in this example) is created automatically, of cause the data type of variable "calc" is Function.
2) Declare and assign an unnamed function to a variable
var varName = function([params]) {funcBody};
For example:
var calc = function(a, b)
{
return a + b;
}
alert(calc(3, 5)); // output 8
Basically, this way is same as 1), except we explicitly assign a Function to a named variable ("calc" in this example).
Remeber a Function is a data type mostly ike Object, it will be much easier to understand code like:
var myObj = {x: 12, y:15}; So to the function data type, right?
Actually we can assign a Function declaration to any place which can be a variable, for example, a property of an Object.
Like below:
var myObj = {
x: 3,
y: 5,
calc: function(a, b) { return a+b;}
};
alert(myObj.calc(myObj.x, myObj.y)); // output 8
3) Declare and assign a named function to a variable
var varName = function funcName([params]) {funcBody};
This is a combination of 1) and 2). As expected, there will be two Function type data created:
One is the auto-created variable with the same name of the function ("funcName"), the other is the variable explicitly declared ("varName").
Both varName and funcName represent the same function instance.
For example:
var calc = function calculate(a, b)
{
return a + b;
}
alert(calc(3, 5)); // output 8
alert(calculate(3, 5)); // output 8
4) Create a Function by "new" operator
Since a Function is a data type most similar to Object, we can create a Function by the "new" operator as well.
var varName = new Function([paraName], funcBody);
Please notice that the parameter names and function body are all strings. You can define as many parameters for the function as you need, JavaScript compiler knows that the last string is the function body. You don't need to add the outmost "{" and "}" to the function body, but it is still fine if adding it from the grammar point of view.
For example:
var calc = new Function("a", "b", "return a + b;");
alert(calc(3, 5)); // output 8
The parameters of the Function constructor accepts instant strings or string variables. This allows you to define function body in advance, and then create the
Function in later step. If the function body is a pretty long string, contact them by "+" is a good idea.
For example:
var p1 = "a"
var p2 = "b"
var body = "return a + b;"
var calc = new Function(p1, p2, body);
alert(calc(3, 5)); // output 8
Creating a Function with only the funcBody means the function has no named arguments.
A dynamically created Function is not compiled when it is "declared". The body of the function is parsed and interpreted by JavaScript engine only when the Function is called, that means, grammar error can only be detected at the time the Function is called.
Creating a function on fly is useful sometimes, below example demonstrates creating operators in less code.
function createOp(operator)
{
return new Function("a", "b", "return a " + operator + " b;");
}
var plus = createOp("+");
var sub = createOp("-");
var multi = createOp("*");
var div = createOp("/");
alert(plus(3, 5)); //output 8
alert(sub(3, 5)); // output -2
alert(multi(3, 5)); // output 15
alert(div(3, 5)); // output 0.6
How to detect whether a variable is a Function data type?
Sometimes we need to know whether a variable is a Function data type. Using typeof operator to detect a Function variable returns "function", so typeof operator is a way.
For example:
function isFunction(obj)
{
return typeof(obj) === "function";
}
jQuery uses a different way to detect Function data type, it uses toString() method. For the reason the built-in function toString() of the Function data type would return the source code of the function body itself, we have to use the toString() function of Object data type.
For example:
function isFunction(obj)
{
return Object.prototype.toString.call(obj) === "[object Function]";
}
I believe there is some reason for jQuery using the later approach, I'd like to recommend this way to detect the Function variable type.
Hope this is helpful to understand what a Function is and how to declare it.
In next part of the article, I'll describe the Object characters of Function.