我创建了两个对象:用户和博客,我需要关联它们。我的想法是为每个创建一个ID然后进行关联。在创建实例时,ID是通过array.length创建的。
associateUserWithBlog函数将博客存储在各自的用户中。在用户实例中,我定义了一个数组,用于存储用户创建的所有博客。 我的问题是,是否有另一种方式来进行这种关联。我以后需要打印所有博客及其所有者(用户),有时我还在努力打印。
function User(name, level, title, id, entry, comment) {
this.name = name;
this.level = level;
this.title = title;
this.id = id;
this.entry = entry;
this.comment = comment;
}
function Blog(blogID, title, userID, blogText) {
this.blogID = blogID;
this.title = title;
this.userID = userID;
this.blogText = blogText;
this.comment = comment;
}
users = new Array();
blogs = new Array();
function associateUserWithBlog(userID, entryID) {
users[userID].entry = entryID;
}
// user with id = 0
userID = users.length
var user = new User(userID, "Bob", "Student", "Mr", new Array())
// blog with id = 0 and user associate with id = 0
blogID = blogs.length
var blog = new Blog(entries.length, "Blog 1", 0, "Welcome Blog 1");
associateUserWithEntry(userID, blogID);
答案 0 :(得分:2)
以下内容创建了一个用户,他拥有任意数量的博客作为关联。
您可以向用户对象添加更多特定行为,并将其转换为模块模式。我添加了一个片段,简要介绍了这样一个对象。
function createUser(userOpts) {
//private members
var name = userOpts.name;
var level = userOpts.level;
var title = userOpts.title;
var id = userOpts.id;
var entry = userOpts.entry;
var comment = userOpts.comment;
var blogs = userOpts.blogs || [];
return {
//All methods to manipulate private data
createBlog:function() {...}
getBlogs: function() { return blogs.slice(); }
//...other methods
};
}
var user = createUser(opts);