-1

I have a set of functions that manage CRUD operations on a database.

I am trying to have a top level function that houses the add, update, delete, etc. functions to keep it clean and organized.

I often see Javascript SDKs that look like users.add(param, param) where I am envisioning that it looks something like:

users = function(){
     add = function(param,param) {
        // do function
     }
}

What is the proper way to to do this?

Ben
  • 51,770
  • 36
  • 127
  • 149
Rob
  • 11,185
  • 10
  • 36
  • 54

5 Answers5

1

A simple way to do it would be to construct it as an object:

var users = {
    add: function(param, param) {
        //do function
    },

    edit: function(param, param) {
        //do another function
    }
    //etc
};
jprofitt
  • 10,874
  • 4
  • 36
  • 46
1

users is usually an object literal, like so:

users = {
    add:function(...) {...}
}

Alternatively, it could be an instanciated object (unlikely in this particular case):

function Users() {};
Users.prototype.add = function(...) {...};

users = new Users();
users.add(...);
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

You can do something like this:

var Users = {
  add: function(a,b) {...},
  remove: function(a) {...},
};

then call:

Users.add(a, b);

or:

var Users = function(options) { this.init(options); };

// Add a static method
Users.add = function(a,b) {...};
// Also add a prototype method
Users.prototype.remove = function(a) {...};

then do this:

var user = User.add(a, b);

or

var user = new User(user_id);
user.remove();    
Tamás Pap
  • 17,777
  • 15
  • 70
  • 102
0
var users = {
    add: function(params) {
        // do stuff
    },
    // more functions
};
Dan Tao
  • 125,917
  • 54
  • 300
  • 447
0

Maybe this could be helpful:

var User = function(name){
    this.name = name;
    this.address = "";
    this.setAddress = function(address){
        this.address = address;   
    }
    this.toString = function(){
        alert("Name: "+this.name+" | Address: "+this.address);   
    }
}
var a = new User("John");
a.setAddress("street abc");
a.toString();

and to manage a list of users:

var Users = function(){
    this.users = new Array();
    this.add = function(name, address){
        var usr = new User(name);
        usr.setAddress(address);
        this.users.push(usr);
    }
    this.listUsers = function(){
        for(var x = 0; x < this.users.length; x++){
            this.users[x].toString();
        }
    }
}

var list = new Users();
list.add("Mickey", "disney Street");
list.add("Tom", "street");
list.listUsers();

working example: http://jsfiddle.net/N9b5c/

BeNdErR
  • 17,471
  • 21
  • 72
  • 103