0

I have this fiddle:

https://jsfiddle.net/moj94s0e/1/

Where I'm playing with two ES6 Classes.

The first one is a simple class, with a constructor and a method (contains).

class Names {
  constructor (names) {
    this.names = names;
  }
  contains (names) {
    console.log(this);
  }
}

The second one is another Class (React component) that uses the contains a method of the first one:

class Hello extends React.Component {
  constructor(props) {
    super(props);

    this.namesInstance = new Names(["Madrid", "Paris"]);
  }

  handleClick = () => {
   this.namesInstance.contains(["Madrid"]);
  }

  render() {
    return <div onClick={this.handleClick}>Hello {this.props.name}</div>;
  }
}

My question is simple: How is it possible that I have access to this in the contains method, considering it is not bound anywhere (nor in a constructor, in the call or declaring it with arrow function)?

If I change it to arrow function, I can see the Class Names logged into the console as well, including the contains method.

I don't understand this behavior.

If someone can help, please.

Paras Korat
  • 2,011
  • 2
  • 18
  • 36
rmartrenado
  • 1,516
  • 1
  • 18
  • 42

1 Answers1

0

This is the expected behaviour of arrow functions.

They're intended for short function expressions in which it has no sense having its own site call scope and, moreover, it's much more handy to be able to access the external this.

bitifet
  • 3,514
  • 15
  • 37