Association Methods in Javascript
Objectives
Associating Objects
let store = { users: [], items: [] };
// initialize store with key of items and users that each point to an empty array
let userId = 0;
class User {
constructor(name) {
this.id = ++userId;
this.name = name;
// insert in the user to the store
store.users.push(this);
}
}
let itemId = 0;
class Item {
constructor(name, price, user) {
this.id = ++itemId;
this.name = name;
this.price = price;
if (user) {
this.userId = user.id;
}
// insert in the item to the store
store.items.push(this);
}
setUser(user) {
this.userId = user.id;
}
}
let bobby = new User('bobby');
let sally = new User('sally');
let trousers = new Item('trousers', 24, bobby);
let tshirt = new Item('tshirt', 8, bobby);
let socks = new Item('socks', 3, sally);
store;
// {users: [{id: 1, name: 'Bobby'}, {id: 2, name: 'Sally'}], items: [{id: 1, name: 'trousers', price: 24, userId: 1}, {id: 2, name: 'tshirt', price: 8, userId: 1}, {id: 3, name: 'socks', price: 3, userId: 2}]}Summary
Resources
Last updated