简体   繁体   English

如何在javascript中关联两个对象?

[英]How can I relate two objects in javascript?

I had create two objects: User and Blog and I need to associate both of them. 我创建了两个对象:User和Blog,我需要将它们都关联起来。 My thought was to create an ID for each and then make the association. 我的想法是为每个创建一个ID,然后建立关联。 The ID is created through array.length at the moment of creating an instance. 该ID是在创建实例时通过array.length创建的。

The associateUserWithBlog functions stores the blog with respective user. associateUserWithBlog函数将博客与相应的用户一起存储。 At user instance I define an array for store all blogs create by user. 在用户实例中,我定义了一个数组来存储用户创建的所有博客。 My question is if there is another way to do this association. 我的问题是,是否还有另一种方式可以进行这种关联。 I'll need later print all the blogs and its owner(user) and sometimes I struggling to print. 稍后,我将需要打印所有博客及其所有者(用户),有时我会很难打印。

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

The following creates a user with any number of blogs owned by him as an association. 以下内容创建了一个用户,该用户拥有与其关联的任意数量的博客。

You can add more specific behaviors to the user object and convert it into a module pattern. 您可以向用户对象添加更多特定的行为,并将其转换为模块模式。 I have added a snippet which gives a brief outline of such an object. 我添加了一个片段,简要介绍了此类对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM