日期:2014-05-16 浏览次数:20454 次
var setup = function () {
alert(1);
return function () {
alert(2);
};
};
// using the setup function
var my = setup(); // alerts 1
my(); // alerts 2因为setup()包裹了返回的函数,它创建了一个闭包(closure),所以你可以使用这个闭包去存储一些私有的变量;var setup = function () {
var count = 0;
return function () {
return (count += 1);
};
};
// usage
var next = setup();
next(); // returns 1
next(); // 2
next(); // 3
var scareMe = function () {
alert("Boo!");
scareMe = function () {
alert("Double boo!");
};
};
// using the self-defining function
scareMe(); // Boo!
scareMe(); // Double boo!这种模式非常有用,当你的函数有一些初始化的准备工作要去做并且只需要做一次(在可以避免的情况下,没有理由去做重复的工作),函数的一部分可能再也不需要了;// 1. adding a new property
scareMe.property = "properly";
// 2. assigning to a different name
var prank = scareMe;
// 3. using as a method
var spooky = {
boo: scareMe
};
// calling with a new name
prank(); // "Boo!"
prank(); // "Boo!"
console.log(prank.property); // "properly"
// calling as a method
spooky.boo(); // "Boo!"
spooky.boo(); // "Boo!"
console.log(spooky.boo.property); // "properly"
// using the self-defined functio