0

I am new to React Native and ES6. I can access outer scope 'this' in this code:

my_function()
{
    this.setState = {};//outer scope this

    return fetch('https://facebook.github.io/react-native/movies.json')
      .then((response) => {
        console.log(this); //this shows the correct outer scope this
        return response.json()})
      .then(...);

}     

But if I write this arrow function out as:

 return fetch('https://facebook.github.io/react-native/movies.json')
        .then(function(response){
           console.log(this); //this becomes some 'DedicatedWorkerGlobalScope' when I am debugging?
           return response.json();
        }).then(...)

I don't understand why this two function is not equivalent?

Tianyun Ling
  • 1,045
  • 1
  • 9
  • 24

1 Answers1

1

Because the arrow functions are automatically bound.

If you want to have the same result you should write:

return fetch('https://facebook.github.io/react-native/movies.json')
    .then(function(response){
       console.log(this); //this becomes some 'DedicatedWorkerGlobalScope' when I am debugging?
       return response.json();
    }.bind(this)).then(...)

I have added ".bind(this)" after the closing "}" of the function.

Paolo Dell'Aguzzo
  • 1,431
  • 11
  • 14