Imagine I have one user
and one other
user. The former would like to follow the latter, which I have designed as a many to many relashionship. How can I do it in Javascript? I need something like user.followers.append(other)
.
In real life you use database connections for that, and you must have a backend already built. But if you're just playing with objects in JS, then you need a User
class with a follow
method.
function User (params) => {
const {
name,
age,
friends = []
} = params
this.name = name
this.age = age
this.friends = friends
this.follow = (newFriend) => {
this.friends.append(newFriend)
}
this.showFriends = () => {
console.log(this.friends)
}
}
Then you create two users.
const user = new User({
name: "Joe",
age: 25
})
const other = new User({
name: "Francis",
age: 27
})
Then you make one dude follow the other.
user.follow(other)
Then you can log the user's friends to see what's up.
user.showFriends()
Make user.followers as array. So that you can push the userid of the user who is trying to follow them.
Eg:
user = {'id': 'current_user_id',
'followers' : ['user_id_1', 'user_id_2'....]
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.