如何将带有 ES6 Rest 的方法添加到 JS 对象

How to add a method with ES6 Rest to a JS object

我有一个 Person 构造函数,我想添加一个应该添加朋友的方法。我想让我的用户传递可变数量的朋友,所以我想到了 ES6 的新 "rest" 特性。可悲的是,我找不到出路。这是我的第一次尝试(错误:"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);

我做错了什么? 非常感谢您的帮助!

由于您在 forEach 中使用了回调,因此 this 未引用该对象。将回调绑定到 this:

Person.prototype.addFriends = function(...a){
   a.forEach(function(d){this.friends.push(d)}.bind(this));
}

由于我们使用的是 ES6,您可以改用 arrow function。箭头函数词法绑定 this 值:

Person.prototype.addFriends = function(...a){
   a.forEach((d) => this.friends.push(d));
}

this,在传递给 forEach 的回调中,不是您在这段代码中的 Person 实例:

Person.prototype.addFriends = function(...a){
   a.forEach(function(d){this.friends.push(d)});
}

您可以使用新的箭头函数来获得正确的上下文:

Person.prototype.addFriends = function(...a){
   a.forEach((d) => {this.friends.push(d)});
}

但这里有一个更优雅的解决方案:

Person.prototype.addFriends = function(...a){
   this.friends.push(...a);
}

forEach 接受回调,通常在全局上下文中调用(window 在浏览器中)。您需要将当前 this 作为第二个参数传递给 forEach

或者可以完全避免整个 this 问题,而只是 concat 数组:

function Person(name){
    this.name = name;
    this.friends = [];
    this.addFriends = function(...a){
      this.friends = this.friends.concat(a);
    }
}

您可以使用 ECMAScript 6 的新功能 -> classes

  1. 定义你的class:

    class 人 {

    constructor(name) {
        this.name = name;
        this.friends = [];
    }
    
    addFriends(friends) {
        // do someting with friends
        this.friends = friends
    }
    

    }

然后你就可以创建 Person 的新实例

var p = new Person("Jack");

并添加一些新朋友

p.addFriends(....)