The utilization of the 'this' keyword within an object is not feasible due to its placement within a separate function

The issue I am facing is while using vue.js, but I believe it might also be applicable in plain JS. The problem arises when I am inside a function that is within another function; I have to reference variables by their full path such as Object.variable instead of simply using this.variable. Is there a way to access variables like this.timer and this.pages directly, instead of having to specify TVComponent.timer or TVComponent.pages?

const TVComponent = new Vue ({
el: '.tvContent',

data:
{
    current_page: 0,
    timer: 0,
    pages: [
      { page: '/', interval: 10 },
      { page: 'tv/calls', interval: 10 },
      { page: 'tv/general', interval: 10 }
    ]
},

methods:
{
  tvTimer()
  {
     setInterval(function() {
        TVComponent.timer++;

        if (TVComponent.timer == TVComponent.pages[TVComponent.current_page].interval) {
           console.log('it is time!!');
        }

        console.log(TVComponent.pages[TVComponent.current_page].page);
     }, 1000);
  },
})

Answer №1

Dealing with the classic issue of this not behaving as expected within a function

A. Utilize the bind method

methods:
{
  tvTimer()
  {
     setInterval(function() {
        // ...
     }.bind(this), 1000);
  },
})

B. Implement a closure

methods:
{
  tvTimer()
  const _this  = this
  {
     setInterval(function() {
        _this.timer ...
     }, 1000);
  },
})

C. Embrace an arrow function

methods:
{
  tvTimer()
  {
     setInterval(() => {
        this.timer ...
     }, 1000);
  },
})

Understanding this concept is crucial in JavaScript to avoid repeating mistakes. I recommend reading this ebook for further insight:

https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch2.md#this-identifier

Answer №2

When you provide a function to setInterval, it is important to note that the function will have its own context. However, if you opt for an arrow function instead, it will use the current context and disregard the one specified by setInterval.

setInterval(() => { ... }, 1000)

Answer №3

The reason for this discrepancy is that the setInterval() function's this object differs from the vue.js this, as they operate within separate scopes.

To resolve this issue, it is recommended to assign the this object to a new variable before entering the problematic function's scope.

let self = this;
tvTimer()
  {
     setInterval(function() {
        self.timer++;

        if (self.timer == self.pages[self.current_page].interval) {
           console.log('it is time!!');
        }

        console.log(self.pages[self.current_page].page);
     }, 1000);
  },

Additional information: https://developer.mozilla.org/en-US/docs/Glossary/Scope

Answer №4

In my opinion, the proper way to handle this is to bind it within the given context. This is a common practice in React classes.

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

Stop the change event from occurring on a textarea when the user clicks on an external cancel button

In a particular scenario, there is a textarea with an autosave feature triggered by the change event. When the textarea is focused on, Save and Cancel buttons appear at the bottom, providing users with options in case they prefer not to simply click outsid ...

Error encountered: The JSONP request to https://admin.typeform.com/app/embed/ID?jsoncallback=? was unsuccessful

I encountered an issue with the following error message: Error: JSONP request to https://admin.typeform.com/app/embed/id?jsoncallback=? Failed while trying to integrate a typeform into my next.js application. To embed the form, I am utilizing the react-ty ...

SignalR fails to trigger client callback function

Currently, I am diving into the world of SignalR and attempting to create a basic message notification system. However, despite my limited understanding of SignalR, I am unable to display the messages after submission. I have researched multiple blogs on ...

Error: The specified element to insert before is not a direct descendant of this parent node

As I work on converting a jquery dragable script to plain javascript, I encountered an issue at the insertBefore point. The error message that pops up is: NotFoundError: Node.insertBefore: Child to insert before is not a child of this node. This particula ...

Observing a peculiar discrepancy in how various versions of JSON.stringify are implemented

Imagine having a deeply nested JS object like the example below that needs to be JSON-encoded: var foo = { "totA": -1, "totB": -1, "totC": "13,052.00", "totHours": 154, "groups": [ {"id": 1, "name": "Name A", " ...

Is there a way to simplify this "stopwatch" even more?

Looking for advice on simplifying my JS stopwatch timer that currently only activates once and keeps running indefinitely. As a newcomer to JS, this is the best solution I could come up with: let time = 0 let activated = 0 function changePic() { if(a ...

Encountered an error: Unable to access the property 'getTotalLength' from a null value

My SVG animation was functioning perfectly on CodePen. However, when I integrated it into my website, it suddenly stopped working. The console displayed the following error message: Uncaught TypeError: Cannot read property 'getTotalLength' of n ...

AngularJS parent selector nearest to the element

I have successfully implemented a code to close a custom popup using jQuery, but I am looking for a solution that utilizes AngularJS instead of jQuery. Can anyone assist me in finding the equivalent of this.closest() in AngularJS? I aim to hide .popOverla ...

Here is a method to display a specific string in the mat-datepicker input, while only sending the date in the backend

enter image description hereIn this code snippet, there is a date input field along with a Permanent button. The scenario is that when the Permanent button is clicked, it should display "Permanent" in the input UI (nativeElements value), but the value bein ...

Unable to display D3.js bar graphs

Hello! I'm attempting to replicate a bar chart from this source but unfortunately, my bars are not displaying properly. I'm confident that I've inputted the correct values for the y and height parameters. Could someone kindly assist me with ...

Ways to efficiently manage session control without repeating it in each route

I'm currently working on a Node.js application using express. I've been checking the session in every route, but now I'm looking for a way to separate this check from my routes. Any suggestions? Below is an example of one of my routes: app ...

Display a specific division depending on the outcome of an Ajax request within a PHP form

My PHP form has a layout similar to this: <form> <div id="inid"> National ID: <input type="text" id="individual_nid" oninput="getIndividualName(this.value)" /> </div> <hr /> name: <div id="individua ...

Building dynamic charts using JSON data in Oracle JET

I am attempting to populate a pie chart using JSON data retrieved from restcountries.eu/rest/v2/all. I use $.getJSON to fetch the data, create a temporary array as the data source, and then bind it to the pie chart. However, I seem to be encountering an er ...

Does the arrangement of props matter in JSX?

Assuming the o object has a key/value pair of: foo: 'bar', can I expect these results to hold true?: // foo will be 'bar' <MyComponent foo='should not override' {...o} /> // foo will be 'overridden' ...

Implement code to execute exclusively on the initial success of react-query

I have a unique scenario where I need to utilize standard useQuery behavior, while also executing a piece of code only on the initial onSuccess event. Although I understand that I can accomplish this using useRef, I am curious if there is an alternative a ...

When attempting to seed, the system could not locate any metadata for the specified "entity"

While working on a seeding system using Faker with TypeORM, I encountered an error during seeding: ...

I encountered a TS error warning about a possible null value, despite already confirming that the value

In line 5 of the script, TypeScript raises an issue regarding the possibility of gameInstanceContext.gameInstance being null. Interestingly, this concern is not present in line 3. Given that I have verified its existence on line 1, it is perplexing as to w ...

Receiving a positive server response without needing to trigger the Ajax route in a NodeJs/Express application

Setting up the login route: app.use('/login', require('./routes/login')); The 'login' module includes the route to display the login HTML page and validate the login using an Ajax call. var router = require('express&ap ...

A function is unable to update a global variable

I have been working on a form that allows users to set the hour, with JavaScript validation in place to ensure there is input in the form. Initially, the global variable "userInputHours" is set to 0. Within the function "validation()", when the user meets ...

Is there a specific method or function that can effectively translate special characters such as into their corresponding representations?

When a user provides input for my script using shell arguments, it would look something like this: Kek kek\nkek\tkek\x43 After receiving the input, Javascript interprets my parameter in a specific way: var parameter="Kek kek\&bs ...