var a = function () { function someSetup() { var setup = 'done'; } function actualWork() { alert('Worky-worky'); //return true; } someSetup(); return actualWork; }(); a(); // 打印出了 Worky-worky
function f() { var a = []; var i; for(i = 0; i < 3; i++) { a[i] = (function (x) { return function () { return x; } })(i); } return a; } var a = f(); console.log(a[0]()); // 0 console.log(a[1]()); // 1 console.log(a[2]()); // 2
var getValue, setValue; (function () { var secret = 0; getValue = function () { return secret; }; setValue = function (v) { secret = v; }; })(); console.log(getValue()); setValue(2); console.log(getValue());
// 迭代器 function setup(x) { var i = 0; return function () { return x[i++]; }; } var next = setup(['a', 'b', 'c']); console.log(next()); // a console.log(next()); // b console.log(next()); // c
// 构造函数 function Hero() { this.occupation = 'Ninja'; } var hero = new Hero(); console.log(hero.occupation);
function Hero(name) { this.name = name; this.occupation = 'Painer'; this.whoAreYou = function () { return "I'm " + this.name + " and I'm a " + this.occupation; }; } var hero = new Hero('Nico'); document.writeln(hero.whoAreYou());
(function (count) { if(count < 5) { alert(count); arguments.callee(++count); } })(1);
// 正则表达式 function replaceCallback(match) { return '_' + match.toLowerCase(); } var s = 'HelloJavaScriptWorld'; console.log(s.replace(/[A-Z]/g, replaceCallback)); // _hello_java_script_world