Retrieve data from a variable that is located within a function that is also

 <script>
        const tally ={
            total: 0,
            increase: function(){
                total++;
                console.log(total);
            }        
        }
        const selectBtn = document.getElementsByTagName('button')[0];
        selectBtn.addEventListener('click', tally.increase, false);

    </script>

When executing this code, I'll encounter an error due to an undefined variable. To resolve this, one solution is to include tally.total within the function. However, I am looking for alternative approaches. Is there another method available?

Answer №1

There is no alternative solution unless you define a global variable outside of the counter.

Here's an example:

var cnt = 0;
const counter = {
    inc: function () {
        cnt++;
        console.log(cnt);
    }
}
const button = document.getElementsByTagName('button')[0];
button.addEventListener('click', counter.inc, false);
<button name="button">click me</button>

However, there is a more efficient way to achieve this. Instead of using cnt, you can use counter.cnt:

const counter ={
            cnt: 0,
            inc: function(){
                counter.cnt++;
                console.log(counter.cnt);
            }        
        }
        const button = document.getElementsByTagName('button')[0];
        button.addEventListener('click', counter.inc, false);
<button name="button">click me</button>

Answer №2

const counter = {
    value: 0,
    increase: function() {
        this.value++;
        console.log(this.value);
    }        
}
const btn = document.getElementsByTagName('button')[0];
btn.addEventListener('click', () => counter.increase(), false);
<button name="button">Click Here</button>

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

Learn how to retrieve the TextBox value from a button click within a Nested Gridview

I am trying to extract the value of a textbox inside a Nested Gridview using jQuery in ASP.NET. When a Button within the Nested Gridview is clicked, I want to display the textbox value in an alert box. Here is an example setup: <asp:GridView ID="Grid ...

Create an interface object in TypeScript with no initial properties

I'm currently developing an app with angular 5 (TS) and I've encountered a problem while trying to initialize an empty object of my interface. The solution that I found and attempted is as follows: article: Article = {} as Article; However, ...

What is the most effective method for transferring and accessing data within a child form component?

This is how I am currently handling it: Parent.vue: // Template <form-child :schema="schema"><form-child> // JS data () { return { schema: [{ // name: '', value: '', type: '' }, { //etc ... }] } } For ...

What is causing the addListener function in the events class to malfunction?

I am a beginner in the world of node.js and attempting to execute this piece of code: var eventlib= require('events'); var emitter= new eventlib(); eventlib.addListener('MessageEvent', function() { console.log('Registered the ...

The textbox is only enabled when a specific selection is made in the dropdown menu

My JavaScript code seems to be malfunctioning: <script language="javascript" type="text/javascript"> function ShowExpenseReport(Expense_Report_ID) { var width = screen.width; var leftpad = (width - 740) / 2; var jsopti ...

Please replace the text with only letters and then submit it without any spaces, periods, commas, or other symbols

Whenever I encounter a form like this, I need to submit it and replace the text in the name field with only letters - no commas, spaces, or special characters. https://i.sstatic.net/9FQnT.png myform.html <script> function fixInput(event) { na ...

Updating the value of each preceding sibling of every checked checkbox using jQuery upon form submission

After extensive research, I discovered that the most effective approach involves using a clever workaround to capture every tick and untick on a dynamic input row with multiple checkbox arrays. However, none of the solutions provided a viable method. I th ...

React-Redux - Implement a button toggle functionality to display or hide additional information

I am currently working on creating a portfolio. One of the functionalities I am trying to implement is a toggle button that will show or hide the details of a specific work when clicked. I have been learning React and Redux, so this project is a great oppo ...

Stop button from being clicked inside a div when mouse hovers over it

I am facing an issue with a div containing a mouseenter event and a button inside it with a click event. The concept is that when the user hovers over the div triggering the mouseenter event, the div becomes "active", allowing the button to be visible and ...

Which Javascript/Css/HTML frameworks and libraries would you suggest using together for optimal development?

Interested in revamping my web development process with cutting-edge libraries, but struggling to navigate the vast array of tools available. The challenge lies in finding a harmonious blend of various technologies that complement each other seamlessly. I& ...

Tips on invoking a method from a JavaScript object within an AJAX request

Considering the following code snippet: var submit = { send:function (form_id) { var url = $(form_id).attr("action"); $.ajax({ type: "POST", url: url, data: $(form_id).serialize(), dataType: 'json', succes ...

What's the best way to implement two AJAX field validations to prevent button redirection on a website?

Can anyone provide guidance on how to implement two ajax field validations for a button to prevent clicking if the data already exists or redirecting to the same page? I am seeking assistance with this issue. Below is the ajax code snippet: function vali ...

How to send parameters through the Google Maps API URL using Vue.js

When using $router.push(), I receive two parameters: {{ this.$route.params.lat }} and {{ this.$route.params.lng }}, which are latitude and longitude coordinates. To access a Google Maps URL, I need to include both of these parameters: https://maps.googlea ...

The jQuery change event is not triggered for <input type="file"> when a file is dropped on the label

I am currently developing a drag and drop file uploader that can be activated by either clicking the label or dragging a file onto the label. The input field includes a jQuery on change event that is triggered when a file is selected. However, it only see ...

Implementing restriction measures for deterring harmful conduct within ExpressJS

Recently, I was alerted to some potential vulnerabilities in the application I'm currently developing, particularly in relation to the JavaScript code on the front-end. These flaws could allow a user to exploit the system by clicking multiple buttons ...

Node Js is a lightweight server that allows for easy querying of URLs

I've been exploring various examples but I'm still struggling to understand how it all functions. My goal is quite simple, or so I thought. I was hoping someone could assist me? The task at hand is to establish a server for clients to connect t ...

While validating in my Angular application, I encountered an error stating that no index signature with a parameter of type 'string' was found on type 'AbstractControl[]'

While trying to validate my Angular application, I encountered the following error: src/app/register/register.component.ts:45:39 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used ...

When using Vue.js router.push, the URL gets updated but the RankerDetail component does not refresh when navigating with a button

I am currently working on a Vue.js project that involves vue-router, and I've encountered an issue with the RankerDetail component. This particular component is responsible for dynamically displaying data based on the route parameter id. Strangely, wh ...

Having difficulty retrieving the necessary information for manipulating the DOM using Express, Ajax, and Axios

When working on DOM manipulation based on AJAX calls, I've encountered an issue where the response is being displayed on my page instead of in the console.log output. This makes it difficult for me to view the data and determine what needs to be inser ...

What is the benefit of using $q.all() with a single promise in AngularJS?

As I delve into this codebase, one snippet keeps popping up: $q.all([promise]).then(responseFunc); However, I find this confusing. After reading the documentation, I wonder why not simply use the following, as it's just a single promise... promise. ...