let bob = {
_name: "Bob",
_friends: ["stackoverflow"],
printFriends() {
this._friends.forEach((f)=> {
console.log(this._name + " knows " + f);
});
}
}
its working fine when I call bob.printFriends();
let bob = {
_name: "Bob",
_friends: ["stackoverflow"],
printFriends() {
this._friends.forEach((f)=> {
console.log(this._name + " knows " + f);
});
}
}
bob.printFriends();
but when I change bob
object printFriends
function to arrow function :
let bob = {
_name: "Bob",
_friends: ["stackoverflow"],
printFriends:()=> {
this._friends.forEach((f)=> {
console.log(this._name + " knows " + f);
});
}
}
If I do not rebind then this
inside the printFriends
refer to window
object. Thats why I am trying to rebind printFriends
bob.printFriends = bob.printFriends.bind(bob);
then bob.printFriends()
is not working as per expectation, giving error:
Uncaught TypeError: Cannot read property 'forEach' of undefined
at Object.printFriends (:5:19)
at :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();