My goal is to enhance my Person constructor by adding a method that allows users to add friends. I wanted to utilize the "rest" feature of ES6 to pass a variable number of friends, but I seem to be stuck. My initial attempt resulted in an error ("Uncaught TypeError: f.addFriends is not a function(…)"):
// Persons creator
function Person(name){
this.name = name;
this.friends = [];
this.addFriends = function(...a){
a.forEach(function(d){this.friends.push(d)});
}
}
// Create three persons
f = new Person("Fanny");
e = new Person("Eric");
j = new Person("John");
// add Eric & Fanny as friends of Fanny
f.addFriends(e,j);
I also tried the following code (no error, but no friends were added):
// Persons creator
function Person(name){
this.name = name;
this.friends = [];
}
Person.prototype.addFriends = function(...a){
a.forEach(function(d){this.friends.push(d)});
}
// Create three persons
f = new Person("Fanny");
e = new Person("Eric");
j = new Person("John");
// add Eric & Fanny as friends of Fanny
f.addFriends(e,j);
Do you know what I'm doing wrong? Thank you for your assistance!