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();