Andrew Krawchyk
3/15/15
Functions declared as functions are available all over: function declaration
functionExpression();
// undefined
functionDeclaration();
// "declaration called!"
var functionExpression =
function() { ... };
functionDeclaration() { ... }
Functions expressed as variables are not available until that variable is declared: function expression
Adds even more dynamism to JavaScript
function transform(tFunc, obj) {
Object.keys(obj).forEach(tFunc)
}
Adds even more dynamism to JavaScript
Useful for:
var throttle = function(fn, frequency) {
frequency || (frequency = 100);
var throttle = false;
return function(){
if (throttle) {
return;
}
throttle = setTimeout(function(){
throttle = false;
}, frequency);
fn.apply(this, arguments);
};
};
.bind(context[, args...])
.call(context[, args...])
.apply(context[, [args])
Functions without names. Sometimes, you just don't need to reuse a function.
New functions create new scope, heavily used for this reason.
Also great for IIFE: immediately invoked function expression
var swigData = (function() {
var d = { ... };
var ret = d.common;
Object.keys(d[options.env])
.forEach(function(key) {
ret[key] = d[options.env][key];
});
return { data: ret };
})();
var globalVar = 'la terre';
(function() {
console.log(globalVar);
})();
// always use var
(function() {
a = 11;
var b = 10;
})();
console.log(a); // 11
console.log(b); // Ref error
Available anywhere in our program
Generally to be avoided
Create scope for your application/website to live in
Return/expose what you need others to access
var globalVar = 'la terre';
(function() {
console.log(globalVar);
var a = 10;
console.log(a); // 10
})();
console.log(a); // Ref error
Available anywhere in your function
Best practice
Can indicate dependencies by passing arguments
Return/expose what you need others to access
(function($, em) {
.... // local scope for globals
})(jQuery, Ember);
Remember values from one context regardless of the context in which they are called
function person(name) {
function get() { return name; }
function set(newName) {
name = newName; }
return { g: get, s: set};
}
Great way to share context between functions
var getSetDave = person('Dave');
var getDave = getSetDave[0];
var setDave = getSetDave[1];
alert(getDave()); //'Dave'
setDave('Bob');
alert(getDave()); //'Bob'
var getSetMary = person('Mary');
var getMary = getSetMary[0];
var setMary = getSetMary[1];
alert(getMary()); //'Mary'
Hides variables in a scope, out of harms way
Great for lazy loading
Only creates a class once and always uses it when asked for again
Example in above link