0

Edit: The question referred to as the duplicate doesn't really answer why arrow functions shouldn't be used to access a non-lexical this. It just answers that arrow functions automatically bind this. My situation is that using an arrow function rather than a normal function cause me to lose the correct reference of this. If you need this outside of the current scope, use a normal function.

I've searched around for a solution to my problem with no luck. Even if I was pointed in the right direction as to what I needed to do would be awesome! My problem essentially is that this.Favkey is undefined here:

const setFavorite = val => {
  console.log(this);
  this.Favorite = val;
  AsyncStorage.setItem(this.Favkey, JSON.stringify(val));
};

This function is getting assigned to a particular object like so:

  for (const obj of objArray) {
    obj.Favkey = `c${obj['-id=']}`;
    obj.Favorite = await getFavorite(obj.Favkey);
    obj.SetFavorite = setFavorite;
  }

And then I am calling this later on a button:

onPress={val => props.myObj.SetFavorite(val)}

In the first block of code, I want this to be the specific obj that I am attempting to enclose the function on. But this.Favkey in setFavorite is undefined. What is printed out instead on console.log(this) is what I think is the whole prototype of Object. So I'm not quite sure what I'm doing wrong here.

pianoman102
  • 541
  • 8
  • 22
  • 1
    An [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) doesn't have it's own context binding. They're not the same as a `function` expression. – Emile Bergeron Jun 27 '19 at 03:24
  • The question referred to as the duplicate doesn't really answer why arrow functions shouldn't be used to access a non-lexical `this`. It just answers that arrow functions automatically bind `this`. My situation is that using an arrow function rather than a normal function cause me to lose the correct reference of `this`. – pianoman102 Jun 27 '19 at 15:13
  • That's the whole point of arrow function and the dupe question has answers that explain every variations that you should be aware of before diving into JavaScript. – Emile Bergeron Jun 27 '19 at 15:45
  • 1
    Oh sorry Emily I wasn't responding to you marking it as a duplicate. That's fine. My comment was mainly for anyone else arriving here with a similar question. My searches never pulled up that linked question so thank you. – pianoman102 Jun 27 '19 at 16:08

1 Answers1

1

Don't use an arrow function - it loses the binding to this which is what you're trying to access. Just use a normal function:

const setFavorite = function(val) {...};
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79