How can i bind this to function of my choice, please guide

Hi,

I am trying to better understand “this” as it is used extensively used in react, but when i came across an example below no matter what binding i use i always keep getting the global value, can any one please help to make it bound to obj only … thanks


function foo() {
console.log( this.a );
}
function doFoo(fn) {

fn(); // 
}
var obj = {
a: 2,
foo: foo
};
var a = "oops, global";
doFoo( obj.foo );

OutPut —> oops global

That isn’t a good example: this referers to the class, so

class MyComponent extends React.Component {
  render() {
    return (<div>{this.props.txt}</div>)
  }
}

this refers to the instance of MyComponent so this.props is the collection of props defined on MyComponent

Ah thanks that is so much better, i was reading kyle simpson books as recommended by some to understand “this”

Event handlers are where you’ll hit an issue - if you don’t use arrow functions in the callback, this inside the callback will be the context of the callback, not the class, so this.props for example won’t exist. So a. use arrow functions, and b. you may need to bind the event handlers anyway if you’re passing them around.

This will come up, and you’ll see the problem straightaway, because your event handlers just won’t work. Don’t worry about it for the minute, it’s a normal problem in JavaScript and it’s easy to get it all working when you do run into it, just ask here if you get stuck trying to fix it.

1 Like