DEV Community

Discussion on: JavaScript Frustration: Classes and Class Properties Transform

Collapse
 
kepta profile image
Kushan Joshi • Edited

I think @elarcis mostly covered it. My humble advise is that Babel is shit and source maps are 💩. If you want to prototype some javascript, create an index.html put some javascript in it (yes any modern javascript, as bleeding edge as async await) and run it in your local browser.

Coming back to your original question, Javascript classes are not a misstep or a badly designed API. The problem fellow devs encounter while learning React and ES2015 together, is that they fail to distinguish which part is Javascript and which part is the Reacts magic (JSX I am looking at you). Now this is not because the developer is incompetent or anything, it is because React and the ecosystem built around it is so damn seamless _(importing css ? importing png? import magic?)_that it feels part of the language. Enough of my rant....

Coming back to your original question, you need to further dig into javascript and the prototypal inheritance.


class Foo {
    method() {
        console.log(this.speak());
    }
    speak() {
        console.log('I am a class');
    }
}
z = new Foo();
z.method(); // I am a class

Surprising to some of the React pundits out in the world, this works!
And anyone who is familiar with how this works in javascript would clearly see why and how it works.

The problem of binding this starts to occur when you separate the context.

setTimeout(z.method, 2000);
// after 2 secs
// Uncaught Error: Cannot read property 'speak' of undefined

This is exactly why you need to bind some of your methods in React class, because they would be called out of context, essentially a different this.

I strongly suggest this book You don't know JS, it really made me understand the whole this wizardry.

Collapse
 
nestedsoftware profile image
Nested Software • Edited

Thanks for the book link!