Is the JavaScript progress bar dysfunctional when used with object-oriented JavaScript code, but functions properly with arrow functions?

After posting a question about the JavaScript progress bar not working with object-oriented JavaScript code on Stack Overflow, I decided to try rewriting the script using arrow functions. Here is the new code:

document.getElementById("barButton").addEventListener("click", callMove);

function callMove() {
  var bar1 = new ProgressBar();
  bar1.move();
}

function ProgressBar() {
  this.elem = document.getElementById("myBar"),
    this.width = 1;
  this.move = () => {
    this.id = setInterval(this.frame, 10);
  };
  this.frame = () => {
    if (this.width >= 100) {
      clearInterval(this.id);
    } else {
      this.width++;
      this.elem.style.width = this.width + '%';
    }
  };
}
#myProgress {
  width: 100%;
  background-color: grey;
}

#myBar {
  width: 1%;
  height: 30px;
  background-color: black;
}
<html>

<head>
  <title>
    This is a OO progress bar test.
  </title>
  <link rel="stylesheet" href="testOOProgressBar.css">
</head>

<body>
  <div id="myProgress">
    <div id="myBar"></div>
  </div>
  <br>
  <button id="barButton">Click Me</button>
  <script src="testOOProgressBar.js"></script>
</body>

</html>

Surprisingly, the code works without using .bind() as mentioned in the original post. What sets apart this arrow function implementation from the constructor/prototype approach discussed previously?

Answer №1

An important feature of the arrow function is that it does not possess its own "this" keyword; rather, it inherits the "this" from the surrounding function in which it is defined.

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

Animating CSS Pixel Fragments

After applying a simple CSS animation that moves size and box shadows from one side of the screen to the other, I am noticing residual pixel fragments left behind. To see this issue in action on Chrome 66, check out the Code Pen: https://i.sstatic.net/Gl ...

Error: The function expressValidator is not recognized in the current environment. This issue is occurring in a project utilizing

I am currently working on building a validation form with Express and node. As a beginner in this field, I encountered an error in my console that says: ReferenceError: expressValidator is not defined index.js code var express = require('express& ...

Babel had a SyntaxError in test.jsx file at line 3, position 11 with an Unexpected token

Having trouble converting JSX to JS with Babel? If you're seeing an error like the one below, don't worry - we can help you fix it: The example code in test.jsx is causing a SyntaxError when transformed using babel test.jsx: SyntaxError: test ...

Switching from jQuery to vanilla JavaScript, iterating through each HTML tag in a loop

Here is my current jQuery code that I am looking to convert into vanilla JavaScript. var elements = []; document.querySelectorAll('*:not(script, style, iframe)').forEach(function(element) { elements.push(element); }); I have tried using d ...

What is the most efficient way to switch perspectives?

I'm currently utilizing storybook to simulate various pages of my application. My concept involves encapsulating storybook within one context for mock data, and then during live application execution, switching to a different context where data is fet ...

Outdated jQuery script no longer functioning (Wordpress)

I recently updated a WordPress site to Version 5.7.2 and now two of the custom Metaboxes are not functioning as expected. The issue seems to be related to the outdated jQuery version used by the Metaboxes. To address this problem, I installed a Plugin cal ...

What could be causing the props to appear empty in a Child component within a Quasar framework and Vue 3 application?

I am facing an issue while passing props to a Child component table in my Quasar Vue3 app. The content is not being rendered, and I can't figure out why. Strangely, the console is clear of any errors. In the parent component, I am creating an object w ...

What is the best way to verify the presence of # in a URL?

Every now and then, due to caching issues, I find myself adding a # to my URL, like so: http://www.example.com/#lang=3201954253 My goal is to find and remove the #lang from the URL if it is present. ...

What could be causing the issue of CSS animation not functioning properly when used in conjunction with a

I am working on creating a switch button with CSS and JavaScript that needs an animation when toggling or clicked. The only issue I am facing is related to the animation. I am wondering if there might be any problem with the positioning (relative, absol ...

the intricacies of resizing a dijit dialog

My dialog is defined as shown below: <div data-dojo-type="dijit/Dialog" id="DetailDialog" class="dijitDialog" ... I have loaded a grid inside the dialog with 10 columns. var dialog = dijit.byId("DetailDialog"); dialog.set("content", this.Details); d ...

What is the rationale behind using both useMemo and createSelector in this code?

This example from the React-Redux documentation showcases how a selector can be utilized in multiple component instances while depending on the component's props. import React, { useMemo } from 'react' import { useSelector } from 'reac ...

Leverage the power of JavaScript functions within the app.component.ts file of

I have a JavaScript file named action.js and I am trying to incorporate it into an Angular project. After doing some research, I found out that the js file should be placed in the assets folder and the path must be referenced in the scripts array within an ...

Ways to update a component when the state changes

When attempting to access components that require authentication, I want to redirect to the login page if the user is not logged in. However, I am facing an issue with initializing the firebase auth object, as there is a small delay. The documentation sugg ...

Utilize moment.js to format a datetime and display the corresponding timezone

I'm having trouble displaying timezones correctly using moment.js. I attempted to use the following code: var result = moment(someDate).format("MM/DD/YYYY HH:mm A Z"); This returns something like: 08/05/2015 06:18 PM +02:00, which is okay, but I w ...

Display the website logo when users share on WhatsApp

My goal is to have my website icon appear in WhatsApp when I share it (similar to the example below). https://i.stack.imgur.com/KCWi8.jpg I initially tried using this code, but it didn't work: <link rel="shortcut icon" href="css/img/favicon/favi ...

The GAS and Bootstrap web form is able to search for and display data in a table format. However, it lacks the functionality to display clickable links or hyperlinks directly from the spreadsheet

Check out this awesome web application https://script.google.com/macros/s/AKfycbyEHj5qtIeCZh4rR6FutBLQ3N9NihreaTv7BFj4_saOfNWJUG0Tn2OtvzQs4zASYHnNiA/exec I'm looking for help to display links or hyperlinks that some cells contain. Any suggestions? ...

Vue.js is throwing an error because it cannot find the property or method "blah" when referencing it during rendering

Can you explain why Vue 2 throws an error indicating that a prop is not defined, even though it is statically defined in the parent template? Note: This error does not occur when I include the JavaScript code within the .vue file's script tag instead ...

How can you assign a value to an HTML Input by dragging an SVG shape or canvas?

I am currently in the process of creating a user interface for setting pricing parameters. There are three categories that need to be visually represented, along with two sliders to determine suggested Buy/Sell prices. To demonstrate my progress so far, I ...

"Implementing a click event handler on a button within an iframe

On my website, I have embedded an iframe containing external content. Within the code of this iframe is a button identified by the id "XYZ." I want to create an onclick function for this button. Here's what I've attempted: $( "#XYZ" ).click(fun ...

Using references to pass variables in TypeScript [Angular 8]

I have several variables within the html of this component that are assigned their values by the typescript file. The declaration in the html is as follows: <h1>{{myproperty1}}<\h1> <h1>{{myproperty2}}<\h1> <h1>{{myp ...