One is a function declaration, and the other is a function expression.
function declaration Elevation:
Say Hi ();
function say Hi () {
Alert ("hi!");
}//This example does not throw an error, because the function declaration is read before the code executes.
anonymous function: var functionname=function (arg0,arg1,arg2) {function Body};
Sayhi (); Error: function does not yet exist
var sayhi=function () {
Alert ("hi!");
};
Don't do this//you can do this
if (condition) {var sayhi ();
function Sayhi () {if (condition) {
Alert ("hi!"); Sayhi=function () {
}else{alert ("hi!");
Alert ("yo!"); };
}}else{
} alert ("yo!");
};
}
7.1 Recursion
function factorial (num) { if (num <= 1) { return 1; else { return num * factorial (num-1 var anotherfactorial = factorial; Factorial = null ; Alert (Anotherfactorial ( 4)); // error!
7.2 Closures
Closures are functions that have access to variables in another function scope. A common way to create closures is to create another function inside one function.
function fn (PropertyName) {
return function (Object1) {
var v1 = Object1[propertyname]; Accessed the external Variable propertyname variable
}
}
7.2.1 Closures and variables
function Createfunctions () {
var result = [];
for (var i=0; i<10; i++) {
Result[i] = function (num) {
return function () {
return num;
}
} (i);
}
}
var funcs = createfunctions ();
for (var i=0; i<funcs.length; i++) {
document.write (Funcs[i] + ' <br/> '); Output 0,1,2,3 ... 9
}
7.2.2 This object
If an HTML element is stored in the scope of the closure, it means that the element cannot be destroyed.
function Assignhandler () {
var element = document.getElementById (' someelement ');
var id = element.id;
Element.onclick = function () {
alert (ID);
};
element = null; variable is set to NULL to dismiss a reference to a DOM object, reduce the number of references, and ensure that the memory it consumes is properly reclaimed
}
7.2.3 Memory leaks
If an HTML element is stored in the scope of the closure, it means that the element cannot be destroyed.
function Assignhandler () {
var element = document.getElementById (' someelement ');
var id = element.id;
Element.onclick = function () {
alert (ID);
};
element = null; variable is set to NULL to dismiss a reference to a DOM object, reduce the number of references, and ensure that the memory it consumes is properly reclaimed
}
JavaScript Advanced Programming (Third edition) seventh chapter function expressions