Created
April 14, 2014 06:42
-
-
Save vikingmute/10621921 to your computer and use it in GitHub Desktop.
闭包,传入函数,匿名函数 in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//inspired by http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386819873910807d8c322ca74d269c9f80f747330a52000 | |
//python version on the way | |
//a javascript clousure sample | |
function testSum() { | |
var argsArr = Array.prototype.slice.call(arguments); | |
function sum() { | |
//clousure can get the acess to outer args and private variable | |
var sumNum = 0; | |
for(var i =0, len = argsArr.length; i < len; i++){ | |
sumNum += argsArr[i]; | |
} | |
return sumNum; | |
} | |
return sum; | |
} | |
var f = testSum(1, 2, 3); | |
var x = testSum(1, 2, 3); | |
console.log(f === x); | |
f(); | |
//pass a function as a parameter | |
var numbers = [1, 2, 3, 4, 5]; | |
function square(x) { | |
return x * x; | |
} | |
numbers.map(square); | |
//map generically use, not only in array | |
var map = Array.prototype.map; | |
map.call(numbers, square); | |
//use it in string | |
var str = 'This is cool stuff'; | |
function upperstr(s) { | |
return s.charCodeAt(0); | |
} | |
map.call(str, upperstr); | |
//anonymous function = callbackk function = lambda in python | |
map.call(numbers, function (x) { | |
return x + 20; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment