[1+1=2]

OneAndOneIs2

« CommunicationThe short book »

Fri, Dec 30, 2011

[Icon][Icon]Better still

• Post categories: Omni, My Life, Programming, Helpful

The previous JS example was all well & good - it used a closure to store the data it needed - but it was a 'public' variable - you could intrude on the object and change the value yourself. This is bad, of course.

THIS is far better: Instead of creating a function object, you have the function create and return a new object, which has access to the lexical scope of the function that created the variable.

Nothing else can access that scope, so you now have a nice private variable. This same approach can give you private data, private methods.. it lays the groundwork for entire encapsulated modules, without having any cluttering of namespaces or use of global variables.

In fact, it's almost like using a slightly old and crippled version of Perl. It's that good.

Try it yourself in your browser's console: Paste the code below in. You can still run count_hundred.count() to increment the value, and I've added the .get() method as well, to return the count without incrementing it. But ONLY by using these methods can you get the value: The data is protected from tampering by its scope.

This is something I just didn't think you could do with JS. I'm almost starting to like it.

var counter = function (start){
    start = typeof start == 'number' ? start : 0;
    return {
        count: function() { return ++start;},
        get:   function() { return start;}
        }
    };

var count_hundred = counter(100);

1 comment

pdh
Comment from: pdh [Visitor]
pretty
31/12/11 @ 11:25

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.
(Line breaks become <br />)
(Name, email & website)
(Allow users to contact you through a message form (your email will not be revealed.)
This is a captcha-picture. It is used to prevent mass-access by robots.
Please enter the characters from the image above. (case insensitive)
 

[Links][icon] My links

[Icon][Icon] Hmm.. new look for twitter? I hope it gets less "Ick! Change! Put it back!" nonsense than Facebook..
08/02/12

[Icon][Icon] Facebook Syndication Error
22/02/12

[Icon][Icon] I last listened to:
Johann Pachelbel - Canon in D major

[Icon][Icon] Most recent photo:
Submersible houseboat

[Icon][Icon]About Me

[Icon][Icon]About this blog

[Icon][Icon]My LQ profile

[Icon][Icon]My /. profile

[Icon][Icon]My Wishlist

[Icon]MyCommerce

[FSF Associate Member]


February 2012
Mon Tue Wed Thu Fri Sat Sun
 << <   > >>
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29        

Search

User tools

XML Feeds

eXTReMe Tracker

Valid XHTML 1.0 Transitional

Valid CSS!

[Valid RSS feed]

powered by free blog software