-
Notifications
You must be signed in to change notification settings - Fork 0
JavaScript
huwenyuan edited this page Feb 5, 2016
·
5 revisions
####Function definition: 1. use var
var x = function() {
console.log("x");
}
2. function declaration
function y() {
console.log("y");
}
####Closure
function sandwichMaker() {
var magicIngredient = "peanut butter";
function make(filling) {
return magicIngredient + " and " + filling;
}
return make;
}
var f = sandwichMaker();
f("jelly"); // "peanut butter and jelly"
f("bananas"); // "peanut butter and bananas"
First Fact: Javascript allows you to refer to variables that were defined outside of the current function.
Second Fact: Functions can refer to variables defined in outer functions even after those outer functions have returned!
A more general-purpose sandwichMaker:
function sandwichMaker(magicIngredient) {
function make(filling) {
return magicIngredient + " and " + filling;
}
return make;
}
var hamAnd = sandwichMaker("ham");
hamAnd("cheese"); // "ham and cheese"
hamAnd("mustard"); // "ham and mustard"
var turkeyAnd = sandwichMaker("turkey");
turkeyAnd("Swiss"); // "turkey and Swiss"
turkeyAnd("Provolone"); // "turkey and Provolone"
A even more convenient way to construct closure, the function expression:
function sandwichMaker(magicIngredient) {
return function(filling) {
return magicIngredient + " and " + filling;
};
}
Third Fact: Closures can update the values of outer variables because closures actually store references to their outer variables.
function box() {
var val = undefined;
return {
set: function(newVal) { val = newVal; },
get: function() { return val; },
type: function() { return typeof val; }
};
}
var b = box();
b.type(); // "undefined"
b.set(98.6);
b.get(); // 98.6
b.type(); // "number"