Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #15919

Re: Question on closure

From JJ <jaejunks_at@_googlemail_dot._com>
Newsgroups comp.lang.javascript
Subject Re: Question on closure
Date 2012-09-17 12:57 +0000
Organization A noiseless patient Spider
Message-ID <XnsA0D1CBA63824Cjaejunksgooglemailco@0.0.0.50> (permalink)
References <e75bb2b7-b525-44d2-a957-5cf70ef25773@z8g2000yql.googlegroups.com>

Show all headers | View raw


justaguy <lichunshen84@gmail.com> wrote:

> I intend to get back on javascripting... what could be a good resource
> to get my hands on this?
> Yes, googling provides some interesting links...
> 
> Here's one specific question, closure, credit of Morris Johns.
> 
> function sayHello(name) {
>   var text = 'Hello ' + name;
>   var sayAlert = function() { alert(text); }
>   sayAlert();
> }
> 
> With closure, the sayAlert local var can be used Multiple times if
> needed vs. alert(text).
> Could we see a more meaningful example?
> 
> Thanks in advance.

I think closure is more like private vs public access where mostly used 
to prevent direct access to a variable like below example.

Here, the MyVal object stores a number where it can only be increased or 
decreased by one and get queried. The number is prevented from being 
directly modified. i.e.: set to specific count.

(function() {
  var theValue = 0;
  myVal = {
    getVal: function() {
      return theValue;
    },
    increase: function() {
      return ++theValue;
    },
    decrease: function(val) {
      return --theValue;
    }
  };
})();

Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Question on closure justaguy <lichunshen84@gmail.com> - 2012-09-15 13:01 -0700
  Re: Question on closure JJ <jaejunks_at@_googlemail_dot._com> - 2012-09-17 12:57 +0000
    Re: Question on closure justaguy <lichunshen84@gmail.com> - 2012-09-17 09:14 -0700
    Re: Question on closure Gene Wirchenko <genew@ocis.net> - 2012-09-17 10:02 -0700
      Re: Question on closure Christoph Becker <cmbecker69@gmx.de> - 2012-09-17 19:23 +0200
        Re: Question on closure Gene Wirchenko <genew@ocis.net> - 2012-09-17 11:13 -0700
        Re: Question on closure Gene Wirchenko <genew@ocis.net> - 2012-09-17 13:56 -0700
          Re: Question on closure JJ <jaejunks_at@_googlemail_dot._com> - 2012-09-17 21:47 +0000
          Re: Question on closure Stefan Weiss <krewecherl@gmail.com> - 2012-09-18 00:06 +0200
            Re: Question on closure Gene Wirchenko <genew@ocis.net> - 2012-09-17 19:55 -0700
            Re: Question on closure Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-09-18 11:14 +0200
  Re: Question on closure Christoph Becker <cmbecker69@gmx.de> - 2012-09-17 19:32 +0200
    Re: Question on closure justaguy <lichunshen84@gmail.com> - 2012-09-17 11:16 -0700

csiph-web