문제

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?

도움이 되었습니까?

해결책

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
};

다른 팁

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(...);

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();    
var users = {
    add: function(params) {
        // do stuff
    },
    // more functions
};

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/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top