There are two main ways to define a function in Javascript: regular(traditional) functions and arrow functions, but they behave differently under the hood. Especially, when it comes to this, scope, hoisting, and usage in framework React Native.
In this blog, we will compare these way in depth. Let's start!!!
1. Syntax
1.1. Regular functions
This type of function can be written in Declaration and Expression
Ex:
1.2. Arrow functions
- Arrow functions were introduced in ES6 (2015), has a shorter syntax
Ex:
Ex:
2. this keyword behavior
2.1. Regular functions
Ex:
2.2. Arrow functions
Ex:
3. Arguments object
3.1. Regular functions
They have access to the arguments object
Ex:
3.2. Arrow functions:
Ex:
4. Constructor capability
4.1. Regular functions
Can be used as constructor with new
4.2. Arrow functions
Ex:
5. Hoisting
6. Applying for React Native (Class component)
In React Native Class component, when use regular functions, we have to bind them in constructor. Why we must do like this, while in Javascript we don't need to bind? Okie, go ahead to dive deep!!!
6.1. Why we need to bind if use regular function?
- In Javascript, JS object methods will auto this binding(when call directly)
Ex:
- In React Native Class components, functions - event handlers are not called immediately. We will break down what exactly is going on under the hood.
👉 Why do functions are called indirectly?
If you would like to call this function right now, you should use like this below:
👉 What is going on when users touch, tap, or click the methods that are passed a reference and why this can be lost if using without binding?=> React Native stores this reference and registers it in its internal event system, linking it to the native touch event (e.g., a tap on iOS or Android).
When the user interacts with the UI, the native platform detects the event and sends a message across the React Native Bridge to the JavaScript thread.
React Native's internal event dispatcher then invokes the handler function, but it does so without binding the this context.
Therefore, if handleClick is a regular class method and not explicitly bound (using .bind(this)), this will be undefined when the method runs.
However, if you bind the method in the constructor (or define it as an arrow function), this will correctly refer to the class instance.
6.2. Why arrow function don't need binding?
6.3. Should we use regular functions or arrow functions in class component?
- There is another way to use regular functions without binding by calling them like this:
But it isn't recommended, because () => this.handleClick() can be created to a new function on every render.
0 Comments