"Encountering a situation where a Typescript function becomes

I am experiencing an issue with the binOp function in my code. The function runs once when called from an expression, but then becomes undefined when called by term. I'm having trouble figuring out why this is happening. I've tried to debug it and review the code several times, but I can't seem to find the root cause. My project is running on localhost using Next.js.

Upon encountering this problem, the following error message is displayed:

TypeError: Cannot read properties of undefined (reading 'binOp')

class Parser {
    tokens: Token[]
    tokIdx: number
    currentTok: Token

    constructor(tokens: Token[]) {
        this.tokens = tokens
        this.tokIdx = -1
        this.currentTok = new Token({type:"null"})
        this.advance()
    }

    advance() {
        this.tokIdx++
        if(this.tokIdx < this.tokens.length) {
            this.currentTok = this.tokens[this.tokIdx]
        }

        return this.currentTok
    }
    
    binOp(func:any, ops:string[]) {
        console.log("here")
        let left: any = func()

        while(this.currentTok.type == TT_MUL || this.currentTok.type == TT_DIV) {
            let opTok = this.currentTok
            this.advance()
            let right = func()
            left = new BinOpNode({leftNode:left, opTok:opTok, rightNode:right})
        }

        return left       
    }

    parse() {
        return this.expression()
    }
    
    factor() {
        let tok: Token = this.currentTok

        if(tok.type == TT_INT || tok.type == TT_FLOAT) {
            this.advance()
            return new NumberNode(tok)
        }
    }

    term() {
        return this.binOp(this.factor, [TT_MUL, TT_DIV])
    }

    expression() {
        return this.binOp(this.term, [TT_PLUS, TT_MINUS])
    }
}

ts playground link

Answer №1

An error occurred: Cannot access 'binOp' as it is undefined

It's crucial to understand that the error doesn't imply binOp itself is undefined, but rather the object that should contain this method is actually undefined. This distinction carries significant importance.


The following line:

return this.binOp(this.term, [TT_PLUS, TT_MINUS])

Will not function properly. Trying to call a method of a class instance in isolation like this results in losing track of the correct value for this.

The value assigned to this depends on how it is invoked. When you execute myObj.method(), this within the method will refer to myObj by default.

All instances of a class share methods. Therefore, if you obtain a standalone reference to a method, there's no way to determine which specific instance it originated from. As a result, this cannot correspond to the expected instance.


To correctly pass a method of a class, you can either use an enclosing function:

return this.binOp(() => this.term(), [TT_PLUS, TT_MINUS])

Or bind the function before passing it:

return this.binOp(this.term.bind(this), [TT_PLUS, TT_MINUS])

See a functional example here

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

Material UI autocomplete is not detecting the options parameter as an array

I am currently working on implementing an autocomplete field that retrieves options from my component's state, which in turn fetches data from the backend. Here is a snippet of my component: export const Person: React.FC<PersonProps> = ({name, a ...

Typescript does not directly manipulate values. For instance, using a statement like `if(1==2)` is prohibited

I am currently developing an Angular application with a code coverage report feature. There is a method where I need to skip certain lines based on a false condition. So, I attempted to create a function in my component like this: sum(num1:number,num2:nu ...

Passing images as props to be utilized with next/image in NextJS

Below is the content of my index.js file: import Head from 'next/head' import Layout, { siteTitle } from '../components/layout' import Homecard from '../components/homecard' import logo from '../public/images/logo.jpg&apo ...

Converting input/select string values into strongly-typed values with Angular 2

I've been searching for a solution for quite some time now, but I'm still a bit confused. The issue is simple: I have a model with a boolean property that I'm mapping to a select element in Angular. The select allows the user to choose betwe ...

Error: Unable to parse string in URI within vscode API

Console LOG displays: \Users\skhan\Library\Application Support\Code\User\summary.txt The loop is used to replace the slashes. It works fine in Windows but not in Ubuntu and Mac. This is an example on OSX 10.11.6. Howev ...

Automate the process of opening an ngbpopover from an Angular 2 component using programming techniques

Currently, I am referring to this specific article in order to integrate Bootstrap with Angular 2. While the instructions in the article are helpful, there seems to be a lack of information on how to pass the popover reference to a component method. The on ...

Passing a JSON object from one page to another using NextJS

I recently started working with NextJS and React. I've created a page called A where I fetch data (a JSON object) from an API using getServerSideProps() for each request and display it. On this page, I have some IconButtons that navigate to another pa ...

How to add an OnClick listener to a cell element in a table built with the Tan

I am currently working on a project using React and trying to implement a table. I want to show an alert when a header cell in the table is clicked, displaying some information. However, I have been struggling to find assistance on adding a click listener ...

Cannot display value in NumericFormat when using MUI TextField due to prefix restrictions

When using MUI TextField with the NumericFormat and prefix prop, there seems to be an issue. If I start typing a number quickly, only one digit gets registered. On the other hand, if I type slowly all my numbers show up but the prefix disappears. All inp ...

Add the specified HTML tag to the existing document. An error has occurred: HierarchyRequestError - The action would result in an invalid node

During my testing of a React/TypeScript project using Jest + Enzyme, I encountered an issue when trying to append an HTML tag. The error occurred with the following unit test code: const htmlTag: HTMLElement = document.createElement('html'); htm ...

Experiencing unexpected behavior with React Redux in combination with Next.js and NodeJS

I'm in the process of developing an application using Next.js along with redux by utilizing this particular example. Below is a snippet from my store.js: // REDUCERS const authReducer = (state = null, action) => { switch (action.type){ ...

Creating a unique optional string array interface in TypeScript

I am looking to create an interface that includes optional string values. Here is what I have in mind: interface IEntity { values: ['RemainingUnits', 'ActualUnits', 'PlannedUnits'] } However, when implementing this inter ...

Mastering Angular Apollo Error Resolution Methods

Hey everyone, I'm facing a problem with apollo-angular and apollo-link-error that I just can't seem to figure out. I've experimented with different approaches but have had no luck catching errors on the client-side of my angular web app. Bel ...

Eliminating null values from a multidimensional array

Is there a way to remove the array elements cctype, cctypologycode, and amount if they are empty? What would be the most efficient approach? { "ccInput": [ { "designSummaryId": 6, "CCType": "A", "CCTypologyCode": "A", "Amount ...

Modifying the menu with Angular 4 using the loggedInMethod

Struggling to find a solution to this issue, I've spent hours searching online without success. The challenge at hand involves updating the menu item in my navigation bar template to display either "login" or "logout" based on the user's current ...

The error message "Undefined value received instead of a string or boolean in Vuetify and nuxt.js rules" indicates that the expected data type was not provided

I recently created an app at my workplace and encountered an error in the text area similar to what I have described in my title. After researching the issue online, I found some information but still struggle to fully grasp the concept. My objective is t ...

leveraging parcel for importing typescript dependencies

I am currently using parcel to process typescript for a web extension. I have installed JQuery and its type definitions via npm. In my typescript file, I have the following at the top: import $ from "jquery"; import "bootstrap"; However, when running run ...

Angular application experiencing issues with opening snackbar notifications

I'm currently working on a user registration application in Angular. My goal is to notify the user upon successful account creation or if an error occurs. I've been attempting to use a snackbar for this purpose, but it's not working as expec ...

The AuthGuard (Guard decorator) is unable to resolve its dependencies according to Nest

My AuthGuard is responsible for checking the JWT token in controllers. I am trying to use this Guard in controllers to verify authentication, but I encountered the following error: Nest cannot resolve dependencies of the AuthGuard (?, +). Please ensur ...

Trigger the identical event to be sent to two distinct functions upon the corresponding button click in Angular 2 using Typescript

I recently implemented a service that fetches JSON data and subscribes to two different variables within my component. These variables are then used by two separate drop-down lists to filter the data accordingly. The filtered data is then sent to another s ...