/*************************************Functions as Objects******************************/
//define a Function object
var funObj = new Function("alert('aaa');");
funObj();
//assign to another variable
var funObj2 = funObj;
funObj2();
/*
* define a Function object with some parameters
* Form:var functionName = new Function("argument 1",..."argument n", "statements for function body");
* Note:The main advantage of declaring a function using the new operator is that a script can create a function after a document loads.
*/
var funObjWithParam = new Function("msg", "alert('aaaa' + msg);");
funObjWithParam('message');
/*************************Function Literals and Anonymous Functions*******************/
//simple use of a function literal
var literObj = function(name) {alert(name);};
literObj('bbb');
//Their primary use is when creating methods for user-defined objects.
//why not just use the following new-style syntax in the constructor function???
//Answer:it might use substantially more memory, as new function objects are created every time you create a new object.
function simpleRoot(name) {
this.name = name;
this.sayHi = function() {alert('Hi my name is '+this.name);};
this.sayAnything = function (msg) { alert(this.name+' says '+msg); };
this.sayHi2 = sayHi2;
function sayHi2() {
alert('Hi my name is '+this.name + "from sayHi2!");
}
}
var fun = new simpleRoot('simpleRootName');
alert(fun.name);
fun.sayHi();
fun.sayAnything('message');
fun.sayHi2();
/*
anonymous function.
var myArray = [2, 4, 2, 17, 50, 8];
myArray.sort( function(x, y)
{
// function statements to do sort
}
);
*/
/****************************************Static Variables*************************************/
/*
function doSum(x, y)
{
doSum.totalSum = doSum.totalSum + x + y; // update the running sum
return(doSum.totalSum); // return the current sum
}
// Define a static variable to hold the running sum over all calls
doSum.totalSum = 0;
document.write("First Call = "+doSum(5,10)+"<<br />>");
document.write("Second Call = "+doSum(5,10)+"<<br />>");
document.write("Third Call = "+doSum(100,100)+"<<br />>");
*/
/***************************************Advanced Parameter Passing****************************/
//read-only length property that indicates the number of parameters the function accepts
//可以接受参数的个数
function paraPass(a, b, c) {}
function paraPass2() {}
alert(paraPass.length);
alert(paraPass2.length);
//possibility by examining the arguments[] array associated with a particular function
//实际传入参数的个数
function paraPass3(a, b, c) {
alert(paraPass3.arguments.length);
}
paraPass3('a');
/*****************************************Using Functions***********************************/
//tips
//1.Define All Functions for a Script First.
//2.Name Functions Well.
//3.Consider Using Linked .js Files for Functions, But Be Cautious.
//4.Use Explicit Return Statements.
//5.Check Arguments Carefully.
//6.Comment Your Functions.