Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic javascript code layout

I have what I think is a fairly simply question but it's one that I can not find the answer to. I have a objects literal that I have created that groups functions, I want to know how I can create a variable that is inside the objects literal and editable/accessable by all the functions within that objects literal. At the moment the only way I know how to do this is create a global variable but I want to stop populating the global in this way. To better describe what I'm looking fiddle

http://jsfiddle.net/aT3J6/

Thanks, for any help.

var clickCount = 0;

/* I would like to place clickCount inside hideShowFn Object but all function inside need access to it, so global within hideShowFn */

hideShowFn = {
    init:function(){  
     $('.clickMe').click(this.addToCount);                
    },

addToCount:function(){
    clickCount++;
    $('<p>'+ clickCount + '</p>').appendTo('body');
    }
}

hideShowFn.init(); 
like image 457
scottmwilliams Avatar asked Dec 06 '25 10:12

scottmwilliams


2 Answers

Create a function which is invoked immediately and returns the object, with the private variable inside the function, like this:

var obj = (function () {
    var privateStuff = 'private';
    return {
        func1: function () { 
            //do stuff with private variable
        },
        func2: function () {
            //do stuff with private variable
        }
    };
}());

http://jsfiddle.net/BE3WZ/

This is the way to have private variables in Functional Programming.

like image 142
Cokegod Avatar answered Dec 08 '25 00:12

Cokegod


http://jsfiddle.net/mattblancarte/aT3J6/10/

Another option would be the pseudo-classical style:

function Constructor(){
  var private = 'private';
  this.public = 'public';

  this.methods = {
    //your methods here...
  };
}

var obj = new Constructor();

Don't forget to use the 'new' keyword, or else you are going to be globally scoped.

Your code translated to this style would be:

function Test(){
  var that = this,
      clickCount = 0;

  this.init = function(){
    $('.clickMe').click(this.addToCount);
  };

  this.addToCount = function(){
    clickCount++;
    $('<p>'+ clickCount + '</p>').appendTo('body');
  };
}

var test = new Test();
test.init();
like image 25
Matthew Blancarte Avatar answered Dec 07 '25 23:12

Matthew Blancarte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!