-1

Class components and function components are both functions, so why does one need to make use of the this keyword in order to use props?

larry burns
  • 169
  • 7
  • 1
    This seems like a basic javascript question not specific to react. If you have "function as a method" you use `this.blah` to access instance properties. If you have a "standalone function" there is no meaningful context so you use argument `blah`. This question might help https://stackoverflow.com/questions/4195970/what-does-this-mean – Yury Tarabanko Jul 06 '19 at 19:08
  • It's not really a React thing, it's Javascript . ES5 introduced classes (which uses `this` as a binder), and the community favored classes until hooks was introduced. Hooks lets you use state without using `this` – stever Jul 06 '19 at 19:10
  • @YuryTarabanko I understand how this keyword works. I think I'm confused because the functional components are written like a constructor function in vanilla js, but they're not constructor functions just regular functions? – larry burns Jul 06 '19 at 19:26
  • @larryburns "the functional components are written like a constructor function" hmm they are not. Constructor function **usually** uses `this` in it. Functional components just take and return things as pure function in FP sense would do. Also you could write them using arrow functions to avoid the confusion (arrow functions can't be used as a constructor :) ). – Yury Tarabanko Jul 06 '19 at 22:16
  • @YuryTarabanko yes you are right, they usually do use `this` in it. I was confused because the function name is capitalized like a reg constructor function. However it seems to just be because all components are capitalized. – larry burns Jul 06 '19 at 23:39
  • @larryburns They are capitalized because this is JSX requirement. `` is transpiled to `React.createElement(Cmp)`, while `` - `React.createElement('cmp')` (notice name is a string) to support html tags. – Yury Tarabanko Jul 07 '19 at 08:20

2 Answers2

1

There is a difference. Classes use strict mode, in which this is set to undefined instead of being bound to the global scope.

Read more here: https://blog.kiprosh.com/understanding-this-keyword-in-javascript-and-react/

ClownBaby
  • 318
  • 3
  • 14
0

Dan Abramov explained this topic on his personal blog from react point of view.

Take a look at it: https://overreacted.io/how-does-react-tell-a-class-from-a-function/