When should I use “this” keyword?

Sergey Stadnik
Frontend Weekly
Published in
2 min readSep 26, 2019

When you browse through Javascript code, you often see function calls prepended with this. keyword, like this.functionName(). However, sometimes this is missing and it's just functionName(). What is the difference and when you should use one over the other?

That depends on whether you React component is functional or class-based.

If your component is a class-based component and functionName is a method of that class, then you must address to it as this.functionName. For example:

class App extends React.Component {
// myFunc is a method of App class
myfunc() {
...
}

render() {
myfunc(); // Error! "myfunc is not defined"
this.myfunc(); // #ThumbsUp
...
}
}

On the other hand, if your component is functional, then functions you declare inside it do not require this keyword to be addressed to, no matter if they are defined with function keyword or as arrow functions.

const App = () => {
function myfunc1(){
...
}

const myfunc2 = () => {
...
}

myfunc1(); // This works
myfunc2(); // This works too
this.myfunc1(); // Error: Cannot read property 'myfunc1' of undefined

...
};

Get more React tips

If you would like to receive helpful tips on React and Javascript like these, enter your email into the box below to subscribe, and you’ll get them in your inbox fresh out of the oven as soon as I publish them.

Originally published at https://ozmoroz.com on September 26, 2019.

Get a weekly email with 8 links to the best articles related to frontend development at http://frontendweekly.co/

--

--

Sergey Stadnik
Frontend Weekly

I am a software developer living in Melbourne, Australia. I like pushing buttons and challenging conventional wisdoms.