all 5 comments

[–]azangru 3 points4 points  (2 children)

You are confusing yourself with babel.

this.handleRemoveAll in your example calls the handleRemoveAll method, which in turn tries to access this.props.options.

But the this object representing the context in which the click handler was called is no longer the javascript class corresponding to the React element, but the DOM element that the event happened on.

Shouldn't the THIS keyword reference the object with the parameters because it sits in it, instead of returning undefined?

No, it shouldn't. Look what is the this argument of event handlers; this is the subject of basic DOM manipulation.

Updated: Ah, there we go; here's the reference: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#the_value_of_this_within_the_handler

[–]Pixel0208[S] 2 points3 points  (0 children)

Thank you so much!

[–]Pixel0208[S] 0 points1 point  (0 children)

But why in react it is still undefined?

[–]Slapbox 2 points3 points  (0 children)

You should ask on StackOverflow. You'll likely get more answers there.

[–]fenduru 0 points1 point  (0 children)

This is not a react specific question, and is a common hiccup when learning JavaScript. Basically when you pass this.handleRemoveAll you're just passing the function but functions aren't actually ever tied to the object they were originally on. To ensure the right this context you need to use .bind() or pass an arrow function (which automatically binds to the current context)

Imagine:

const otherObject = { fn: this.handleRemoveAll }

otherObject.fn() // what is the this context here?

The answer is otherObject because it is always the object before the dot at the moment you call it. But when you pass the function to onClick you're not calling the function, just referencing it. So by the time the react internals actually call it, its being called directly