This code demonstrates a challenge or two when using JavaScript classes and the this keyword.

class Foo {
    constructor(abc) { this.abc = abc; }
    bar() { console.log( "abc:", this.abc ); }
}

const foo = new Foo( '123' );
foo.bar();

const stolen = foo.bar;
try {
    console.log( "A stolen version: ", stolen() );
}
catch( error ) {
    console.log( "Something went wrong!" )
}

console.log( "If we bind it, does it work?" );
foo.bar.bind(foo)();

What do you think it does?

abc: 123
Something went wrong!
If we bind it, does it work?
abc: 123

Surprised? Do you love the way you have to call the function when you want it to do what it should do. I don’t, FWIW. :)

This is a contrived example. It does, hopefully, show you the power of JavaScript in that functions are first class, and that there is complexity in their linkage to this, and what happens when you passing these functions around. Using functions as first class objects like this is a very common thing inside any of the JavaScript frameworks like VueJS, ReactJS and anything else out there. When you layer on the complexity that comes from using JSX, or Babel, then you start to lose the connection to what this has become, because this is really about the relationship of the callee, which can get easily obscured.

If you have been doing JS for a while, you are probably at least aware of these landmines. But, lots of frameworks still force you to retain arcane lore about when to bind, when to use call and whether you can use arrow functions or not (you generally can’t since arrow functions don’t carry this with them).

ReactJS did require you to know about all things this if you were using components with state, until recently. Then, they introduced hooks. To me, the most important thing about hooks has nothing to do with the syntax or reasoning.

It’s this statement that makes all the difference in my recent code.

Classes confuse both people and machines

Hooks permit you to write code that never uses classes, and as such, you never have to worry about all the bizarre behavior of this.