0

I have the following code . I expected it to

  1. Print the person object within UnBoundFx as it is set in the bind method
  2. The final person.name to print "changed name"

But actually it prints undefined and the actual name "test" Can you please help me understand what i am missing from understanding how bind words?

  let person ={
  name:"test",
  getStr: ()=>{
    console.log(person.name)
  }
}

let unBoundFx = ()=>{
  console.log(this)  
  this.name = "changed name";  
} 

let boundFx = unBoundFx.bind(person)
boundFx()

console.log(person.name)
punjabi
  • 49
  • 9
  • This has been answered here: https://stackoverflow.com/questions/33308121/can-you-bind-this-in-an-arrow-function – iPirat Feb 01 '21 at 12:14
  • Does this answer your question? [Can you bind 'this' in an arrow function?](https://stackoverflow.com/questions/33308121/can-you-bind-this-in-an-arrow-function) – iPirat Feb 01 '21 at 12:22

2 Answers2

2

You cannot override the this context of an arrow function. This

let unBoundFx = function () {
  console.log(this)  
  this.name = "changed name";  
} 

would work.

Arrow functions capture the value of this when they are created and there is no way to change it from the outside.

idmean
  • 14,540
  • 9
  • 54
  • 83
1

bind creates a new function which calls the original function in a way that contextually sets the this value.

Arrow functions don't have a this value to set, they pull it from the parent scope lexically.

This cannot be overridden.

If you want to control the this value with bind then create unBoundFx with a function expression or function declaration.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335