Is it possible for arrow functions to be hoisted within a class in JavaScript?

class App {
  constructor() {
    this.canvas = document.createElement('canvas');
    document.body.appendChild(this.canvas);
    this.ctx = this.canvas.getContext('2d');

    this.pixelRatio = window.devicePixelRatio > 1 ? 2 : 1;

    window.addEventListener('resize', this.resize.bind(this), false);
    this.resize();

    window.requestAnimationFrame(this.animate);
  }

  resize() {
    this.stageWidth = document.body.clientWidth;
    this.stageHeight = document.body.clientHeight;
  }

  animate = () => {
    this.test(); // ---> here!
  };

  test = () => {
    console.log('here!');
  };
}

window.onload = () => {
  new App();
};

Why can an arrow function call another method within the same class without being hoisted, when regular functions cannot? Is this a unique characteristic of arrow functions in classes?

Answer №1

Although arrow functions do not go through the hoisting process, what you have here is more than just arrow functions - you are utilizing class fields which are a shorthand for assigning a value to the instance within the constructor (at the start of the constructor, immediately after any super calls). Your code can be simplified as:

class App {
  constructor() {
    this.animate = () => {
      this.test(); // ---> here!
    };

    this.test = () => {
      console.log('here!');
    };
    this.canvas = document.createElement('canvas');
    // ...
  }
}

This is not an issue related to hoisting.

First, this.animate is assigned a function. Then, this.test is assigned a function. Lastly, after a requestAnimationFrame, this.animate is executed.

For a simpler example:

const fn1 = () => {
  fn2();
};
const fn2 = () => {
  console.log('fn2');
};

fn1();

As long as the line that assigns the function to the variable runs before the function is called, everything should function correctly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to securely store a client secret within a JavaScript application?

What is the best way to safeguard a client secret in a JavaScript application in order to ensure it is inaccessible to unauthorized users? Specifically, I am working with an AngularJS SPA. In my case, the client secret is a guid created during login and t ...

Show an image in a specific location on the webpage using JavaScript/jQuery

Is there a way for me to show a visual element at specific coordinates on the browser screen? For example, let's say I have calculated dynamic offsets of { left: 336, top: 378 }, and I would like to display a small line or image at that position. Is ...

Mastering state management for various input types in React

Developing a proof of concept for showcasing tennis player details on a webpage. The page can display information for any number of players, and the user should be able to update all player details simultaneously. I have created 3 components: PlayersPage, ...

What is the best way to retrieve an array of objects that have a property matching another array?

In my array, I have data structured like this: array = [ { name: "john", tag: ["tag1", "tag2"] }, { name: "doe", tag: ["tag2"] }, { name: "jane", tag: ["tag2", "tag3"] } ]; My goal is to create a new array of objects that only contain elements with ...

Retrieve information stored within an object's properties

Possible Duplicate: Accessing a JavaScript Object Literal's Value within the Same Object Let's take a closer look at this JavaScript object var settings = { user:"someuser", password:"password", country:"Country", birthplace:countr ...

Passing in additional custom post data alongside serializing with jQuery

function MakeHttpRequest( args ) { var dataToSend = "?" + $("form[name=" + args.formName + "]").serialize(); $.ajax({ type: "POST", url: args.url + dataToSend, data: { request: args.request }, su ...

`Is there a specific location for this code snippet?`

Recently, I stumbled upon a script that enables website screen scraping. For instance, you can check out an example on JsFiddle The issue arises when I attempt to incorporate another script from "Embed.ly" This specific script enhances a provided link and ...

Design a table within an mdDialog that allows for editing of data presented in JSON format

I'm attempting to implement a dialog using JSON data. $scope.showAttributeData = function(data) { $scope.feature = data console.log($scope.feature) var that = this; var useFullScreen = ($mdMedia('sm') ...

The .forEach() method in Javascript is not suitable for DOM nodes as they are subject to change during the iteration

Having an issue with moving all DOM elements from one node to another, I initially used this code: div.childNodes.forEach((n) => me.container.appendChild(n)); However, I noticed that only half of the nodes were being copied. It seems that the problem ...

What's the most effective method to incorporate additional events into this element using the conditional operator?

Looking for help with this code snippet: <span role="link" tabindex="0" :class="tabDetails.showPayment ? 'link' : ''" @click="tabDetails.showPayment ? cTab('payments') : null" ...

Unexpected outcome when converting a while loop to a .forEach statement

Exploring a practical demonstration of sorting an array of objects based on multiple properties, the code implementation involves a while loop (refer to students1 in the snippet below). I attempted to streamline this process by using .forEach, but encounte ...

Navigating in a Curved Path using Webkit Transition

Currently, I am working on a simple project to learn and then incorporate it into a larger project. I have a basic box that I want to move from one position to another using CSS webkit animations and the translate function for iOS hardware acceleration. I ...

Encountering difficulties with image processing on a web page

Recently, I've been experimenting with uploading an image and converting it to a grayscale version on my webpage. Oddly enough, the javascript code works perfectly when tested locally but fails to generate the grayscale image once integrated onto the ...

Guidelines for deploying a node.js REST API application successfully in a production environment

As I venture into the world of node.js apps, I find myself faced with a dilemma. I've created a REST API using node.js that functions perfectly on my local machine. However, when I attempt to build it using webpack, I'm uncertain about how to run ...

Deciphering the mechanics of collection referencing in mongoose

Today, I am delving into the world of using references in mongoose for the first time. I am trying to figure out how to save a template with a user ID. Do we need to retrieve the createdBy value from the client, or can it be inserted into the templateSchem ...

Client-Specific User Portal

Looking for some support on the back end of things. We are in the process of creating a portal where users will be directed to their specific landing pages upon logging in, providing access to files they have signed up for. Our team is exploring the use ...

While creating a NodeJS backend to complement a ReactJS frontend, I am continuously encountering a 500 error

I've been testing my NodeJS backend with Insomnia and it's working perfectly fine there. However, whenever I try to access the frontend, I keep getting a 500 error. It's puzzling because the endpoint is functioning correctly in the testing p ...

Data from HTML not being transferred by Angular Forms

I am facing an issue with transferring input data from HTML's <select> element to Angular Forms. Let's take a look at my code first. File Name: home-page.component.html <form [formGroup]="rForm" (ngSubmit)="addPaste(rForm.value)"> ...

Exploring the power of Vue.js with dynamic HTML elements and utilizing Vue directives within Sweet Alert

new Vue({ el: '#app', data(){ results: [] } }); I need assistance with implementing Vue directives, events, etc. within the markup of a Sweet Alert. The goal is to display an alert using Sweet Alert that include ...