【发布时间】:2015-10-23 01:11:25
【问题描述】:
我创建了两个对象:用户和博客,我需要将它们关联起来。我的想法是为每个人创建一个 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);
【问题讨论】:
-
您可以通过将一个设置为另一个的属性来直接关联它们:
Blog.user = new User('name', 'level', ...)。 -
您应该将博客作为关联保留在用户内部。由于用户与博客的关系是一对多的,我建议您在用户对象中创建一个博客数组。这样删除博客不会删除用户。删除用户将删除他的所有博客。
标签: javascript logic