I'd like to be able to use classes to create client objects and add address objects to an array within them.
let client = new Client ('A123', 'John', 'Smith', avatarUrl);
client.address('home').add(address);
class Client extends Name {
constructor(clientRef, firstName, lastName, profilePic) {
super (firstName, lastName, profilePic);
this._id = clientRef;
this.addresses = [];
}
addAddress (address, label = 'main') {
address = {...address, label}
this.addresses.push(address);
}
removeAddress (label = 'main') {
this.addresses = this.addresses.filter((element) => { return element.label != label; });
}
}
This is what I'm trying to create, but it doesn't work.
class Client extends Name {
constructor(clientRef, firstName, lastName, profilePic) {
super (firstName, lastName, profilePic);
this._id = clientRef;
this.addresses = [];
}
address (label = 'main') {
add (address) {
address = {...address, label}
this.addresses.push(address);
}
remove () {
this.addresses = this.addresses.filter((element) => { return element.label != label; });
}
}
}
You're trying to assign values to a class method as if it were a key-value object store. It's a function that will return a null reference without a return statement. What you need to do it return a key-value store that has the methods you want, like this:
class Client extends Name {
constructor(clientRef, firstName, lastName, profilePic) {
super (firstName, lastName, profilePic);
this._id = clientRef;
this.addresses = [];
}
address (label = 'main') {
return {
add: (address) => {
address = {...address, label}
this.addresses.push(address);
},
remove: () => {
this.addresses = this.addresses.filter((element) => { return element.label != label; });
}
}
}
}
What you can do is to return an object holding these functions, but you need to ensure that this points to the original Client object, and for that, you could utilize arrow functions:
class Client extends Name {
constructor(clientRef, firstName, lastName, profilePic) {
super(firstName, lastName, profilePic);
this._id = clientRef;
this.addresses = [];
}
address(label = 'main') {
return {
add: (address) => {
address = {
...address,
label
}
this.addresses.push(address);
},
return: () => {
this.addresses = this.addresses.filter((element) => {
return element.label != label;
});
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With