c10b10
c10b10

Reputation: 357

Why using call to overwrite `this` in a parent component callback does not work?

Assuming the Parent component is rendered somewhere and the a element in its child is clicked, the following code will result in logging: Parent {props: ...} 'Hello from child' instead of what I'd expect, i.e.: Child {props: ...] 'Hello from child'.

Isn't using call supposed to overwrite the this reference in the callback? What am I missing?

class Parent extends Component {
 constructor() { /* ... */ }
 myCallback(text) { console.log(this, text); }

 render() {
   return (
     <Child callbacks={{cb1: this.myCallback.bind(this)}} />
   );
 }
}

class Child extends Component {
 constructor() { /* ... */ }
 onClick(e) {
   // ...
   this.props.callbacks.cb1.call(this, 'Hello from child');
 }

 render() {
   return (
     <a href='#' onClick={this.onClick.bind(this)}>Link</a>
   );
 }
}

Upvotes: 0

Views: 81

Answers (1)

Felix Kling
Felix Kling

Reputation: 816462

Isn't using call supposed to overwrite the this reference in the callback? What am I missing?

The this value of a bound function (this.myCallback.bind(this)) cannot be changed, no matter how the function is called.

Upvotes: 1

Related Questions