函数声明为箭头函数,以后想与其他对象重新绑定吗?

时间:2018-10-20 14:28:58

标签: javascript ecmascript-6 arrow-functions

let bob = {
   _name: "Bob",
   _friends: ["stackoverflow"],
   printFriends() {
      this._friends.forEach((f)=> {
         console.log(this._name + " knows " + f);
      });
   }
}

当我打电话给bob.printFriends();

时,它的工作正常

 let bob = {
       _name: "Bob",
       _friends: ["stackoverflow"],
       printFriends() {
          this._friends.forEach((f)=> {
       	     console.log(this._name + " knows " + f);
          });
       }
    }
bob.printFriends();

但是当我将bob对象printFriends的功能更改为箭头功能时:

let bob = {
   _name: "Bob",
   _friends: ["stackoverflow"],
   printFriends:()=> {
      this._friends.forEach((f)=> {
         console.log(this._name + " knows " + f);
      });
   }
}

如果我不重新绑定,则this内的printFriends引用window对象。这就是为什么我试图重新绑定printFriends

bob.printFriends = bob.printFriends.bind(bob);

然后bob.printFriends()未能按预期工作,并显示错误消息: 未捕获的TypeError:无法读取未定义的属性'forEach'     在Object.printFriends(:5:19)     在:1:5

let bob = {
   _name: "Bob",
   _friends: ["stackoverflow"],
   printFriends:()=> {
      this._friends.forEach((f)=> {
         console.log(this._name + " knows " + f);
      });
   }
}

bob.printFriends = bob.printFriends.bind(bob);
bob.printFriends();

0 个答案:

没有答案