我有一个 Person 构造函数,我想添加一个应该添加朋友的方法。我想让我的用户传递可变数量的朋友,所以我想到了 ES6 的新“休息”功能。遗憾的是,我找不到出路。这是我的第一次尝试(错误:“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);
我也尝试了以下代码(没有错误,但没有添加朋友):
// 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);
我究竟做错了什么?非常感谢您的帮助!