When attempting to invoke a method within another method in TypeScript, an error is thrown: "TypeError: this.print

Within my main.ts file:

import { App } from './app';
import './styles.scss';

ready(new App().init);

function ready(fn) {
  if (document.readyState !== 'loading'){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

I also have an app.ts file:

export class App {
    constructor() {

    }
    private print = (str: string) => console.log(str);
    init(){
        this.print('test');
    }
}

Upon running this setup with the ts-loader in webpack, using a tsconfig.json that looks like this:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true,
        "lib": ["es5", "dom", "es2015.iterable"]
    }
}

An error occurs: Uncaught TypeError: this.print is not a function at HTMLDocument.App.init (app.ts:17)

Attempts were made to define the method as private print(str){ console.log(str); }, but unfortunately, this did not resolve the issue.

Is there any way to ensure that the method call within the init() function works correctly?

EDIT: I forgot to mention, I am utilizing webpack v. 1.14.0 and TypeScript 2.1.5 (also tested with 2.1.4).

Answer №1

One issue is that passing new App().init without binding it causes the this context to be different than expected when executed.

To solve this, try:

let app = new App();
ready(app.init.bind(app));

Alternatively, consider:

export class App {
    constructor() {
        this.init = this.init.bind(this);
    }

    private print = (str: string) => console.log(str);

    init() {
        this.print('test');
    }
}

Another approach is using an arrow function:

export class App {
    constructor() {}

    private print = (str: string) => console.log(str);

    init = () => {
        this.print('test');
    }
}

Keep in mind that arrow functions add the method as a property of the instance rather than the prototype of the class. This may cause issues if you plan to subclass the App class and override the init method while needing to call super.init.

Answer №2

An easy fix is to simply do the following:

import { Application } from './application';
const myApp = new Application();
initialize(() => myApp.setup());

This adjustment won't impact inheritance, prototypes, or alter the functionality of class Application.

However, it's worth noting that Nitzan Tomers provided insightful information in their response that should not be overlooked.

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

Preventing hyperlinks within a table from being recognized as the selected table row

I encountered a small issue while working on a webpage where clicking on a link within a table cell causes the entire row to be marked as clicked. However, I want only the link to trigger the click event, not the entire cell. You can view the jsfiddle he ...

Enhancing template-driven forms with validation directly from a component in Angular 6

When working with Angular 6, there are two main approaches for creating forms: The Model-driven approach The Template-driven approach In the Model-driven approach, validators are defined within the component code. On the other hand, in the Template-driv ...

What are the best strategies to troubleshoot issues during NPM Install?

I keep encountering errors during the npm install process, but everything works fine when I use npm install --force in my local environment. However, the issues persist during the repository build as my .yaml file script contains "npm install". Can anyone ...

Having trouble parsing multiple JSON rows in JavaScript

I tried using the twitterapi to fetch my friends list in php and encoded the result as a json array. However, I'm facing difficulty parsing the json array in javascript. I have confirmed that the json array generated by the php code is valid. Below is ...

Map markers for Google Places search not displaying properly

I am currently working on a demo to showcase the functionality of a future search feature. My goal is to query Google for information based on an address or area and then display the area bounds along with nearby places. To achieve this, I am utilizing too ...

Reading text files line by line in TypeScript using Angular framework is a valuable skill to have

Struggling with reading text files line by line? While console.log(file) may work, it doesn't allow for processing each individual line. Here's my approach: In api.service.ts, I've implemented a function to fetch the file from the server: ...

Inquiries regarding JavaScript syntax in a nutshell

I have come across this syntax numerous times, but my attempts to search for it on Google have been unsuccessful. I am hoping to find some help here: <script> (function(){ //code goes here })(); </script> Can someone explain ...

Obtain data transmitted via POST method from JavaScript to PHP

When working with Javascript and JQuery, I am sending an object via post in the following manner: var myobj = {}; myobj['test'] = 1; myobj['child'] = {}; myobj['child']['test2'] = 2; var myvar = 123; $.ajax({ type ...

Can text be inserted into an SWF file using ASP.NET or Javascript via an online platform?

I am managing a website that features videos created by a graphic designer who updates and adds new content regularly. I am looking to add dynamic text to these videos after a specific amount of time, such as "Hosted by XXX". However, I am hesitant to ask ...

The JSX element with type 'Component' does not support any construct or call signatures at this time

I am facing an issue with the following code snippet const pageArea = (Component:ReactNode,title:string) => ({ ...props }) => { return ( <> <div> { Component && (<Component { ...

Feeling uncertain about how to utilize AJAX using the XMLHttpRequest object

The JavaScript function is: function loadData() { const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { const data = xhttp.responseXML.documentElement.getElement ...

What is the best method for playing raw audio wav files directly in a web browser?

I'm currently attempting to play wav raw data in the browser that is being transmitted from a Node.js server via socket.io. The main goal is to play the receiving data as quickly as possible without waiting for all the data to be received. I initially ...

Developing a C# MVC platform that allows users to save canvas designs as image files on the server, with the added functionality of

I am in the process of developing an administrator system that allows users with admin privileges to create new user accounts. One of the requirements for creating a user account is uploading a photograph. To enhance user experience, I have integrated a f ...

Create a function that accepts a class as a parameter and outputs an object of that class

I am working on an instantiator function that generates an instance of a provided class: declare type ClassType = { new (): any }; // known as "ParameterlessConstructor" function createInstance(constructor: ClassType): any { return new constructor(); ...

Accordion is having trouble expanding fully

My accordion is causing some trouble. When I try to open one section, both sections end up opening. I want it to toggle, so that only one section opens at a time based on my click. Switching the display from flex to column fixes the issue, but I don' ...

Difficulty with the D3.js grid and tick functionality

Dealing with x-axis grid line formatting issues in a D3.js graph that I've created. var data = [{ x: '12-May-12', y: 5 }, { x: '30-Apr-12', y: 28 } // more data points listed here var margin = { top: 30, ...

How can I connect a jQuery slider to dynamically update a div's content?

I am trying to update the content of a Message div based on the position of my slider. Since my slider only has 5 positions, I need to display 5 different messages depending on which position is selected. Does anyone know how to accomplish this? Here is t ...

Validate if the user is actively scrolling; if not, automatically adjust the scroll position to the bottom

I am currently developing a chat site where the chat box updates every 200 milliseconds. I have managed to reposition the scrollbar to the bottom when a new message is loaded. However, I encountered a problem - whenever a user tries to scroll to the top, t ...

Issues with the Winston transport for Loggly are causing inconsistent performance

I have implemented Winston with 3 transports: Console, File, and Loggly (using https://github.com/loggly/winston-loggly-bulk). While the Console and File transports are functioning properly, I am facing an issue with the Loggly transport. It only logs my ...

What are the various functions that an Alert button can serve in Ionic?

What are the potential choices for the role designation of a button within an Alert using the Ionic framework (v5)? The official documentation only lists cancel: https://ionicframework.com/docs/api/alert#buttons If desired, a button can have a role prop ...