javascript的閉包

最近看到一篇很好的文章,截取了其中的一段。分享一下。


Once upon a time:

There was a princess...

function princess() {

She lived in a wonderful world full of adventures. She met her Prince Charming, rode around her world on a unicorn, battled dragons, encountered talking animals, and many other fantastical things.

    var adventures = [];

    function princeCharming() { /* ... */ }

    var unicorn = { /* ... */ },
        dragons = [ /* ... */ ],
        squirrel = "Hello!";

But she would always have to return back to her dull world of chores and grown-ups.

    return {

And she would often tell them of her latest amazing adventure as a princess.

        story: function() {
            return adventures[adventures.length - 1];
        }
    };
}

But all they would see is a little girl...

var littleGirl = princess();  //調用這個方法後,返回一個對象,帶有講故事的方法(story),調用這個方法,還能得到公主的冒險經歷故事。

...telling stories about magic and fantasy.

littleGirl.story();

And even though the grown-ups knew of real princesses, they would never believe in the unicorns or dragons because they could never see them. The grown-ups said that they only existed inside the little girl's imagination.

But we know the real truth; that the little girl with the princess inside...

...is really a princess with a little girl inside.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章