2013-06-02 72 views
-1

我有一組管理數據庫上的CRUD操作的函數。JavaScript函數的格式化()

我想擁有一個頂級功能,其中包含添加,更新,刪除等功能,以保持清潔和組織。

我經常看到的樣子users.add(param, param)我在哪裏設想,它看起來像的Javascript軟件開發工具包:

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

什麼是做到這一點的正確方法?

回答

1

一種簡單的方法來做到這將是構建其作爲對象:

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

    edit: function(param, param) { 
     //do another function 
    } 
    //etc 
}; 
0
var users = { 
    add: function(params) { 
     // do stuff 
    }, 
    // more functions 
}; 
1

users通常是一個對象常量,像這樣:

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

可替代地,它可以是一個instanciated對象(在這種特殊情況下不太可能):

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

users = new Users(); 
users.add(...); 
1

你可以做這樣的事情:

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

然後調用:

Users.add(a, b); 

或:

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) {...}; 

然後做到這一點:

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

var user = new User(user_id); 
user.remove();  
0

也許這可能是有益的:

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

,並管理用戶的列表:

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

工作示例:http://jsfiddle.net/N9b5c/