Skip to content

Instantly share code, notes, and snippets.

@chuck0523
Created September 17, 2015 17:13
Show Gist options
  • Save chuck0523/96729b2668af1a44592f to your computer and use it in GitHub Desktop.
Save chuck0523/96729b2668af1a44592f to your computer and use it in GitHub Desktop.
// 出力用
var log = function(x) {
console.log(x);
};
// シンプルな形
function init(n) {
var name = n;
function display() {
log(name);
}
display();
}
// 初めてのクロージャ
function makeFunc() {
var name = "chuck";
function displayName() {
log(name);
}
return displayName;
}
var myFunc = makeFunc();
init('chuck'); // chuck
myFunc(); // chuck
log(myFunc); // [Function: displayName]
log(typeof myFunc); // function
// 関数ファクトリ
function makeAdder(x) {
return function(y) {
return x + y;
}
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
log(add5(2)); // 7
log(add10(2)); // 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment