Various approaches to declaring a function in TypeScript

Within my TypeScript module, I have the following code snippet:

import app = require("durandal/app");
import ko = require("knockout");

class Screen1 {
    method1(arg: string): string {
        return "Hello";
    }

    method2 = (arg: string): string => {
        return "Hello";
    };
}

export = Screen1;

This TypeScript code compiles into the JavaScript below:

define(["require", "exports"], function (require, exports) {
    "use strict";
    var Screen1 = (function () {
        function Screen1() {
            this.method2 = function (arg) {
                return "Hello";
            };
        }
        Screen1.prototype.method1 = function (arg) {
            return "Hello";
        };
        return Screen1;
    }());
    return Screen1;
});

I can observe the differences in the output for each method, but what practical impact does it have at runtime? My suspicion is that it may alter the context of `this` within those methods, but I am uncertain about how to thoroughly investigate this.

(One aspect of TypeScript that often perplexes me is the array of options available to accomplish seemingly identical tasks, leading to subtle distinctions - such as defining a class. I find it quite confusing and overwhelming)

Answer №1

When utilizing this within a function and passing that function to another, the difference in functionality becomes apparent. Regular functions do not retain the value of this from their declaration context, whereas arrow functions do. If you assign a regular function to a variable and invoke it, this will not refer to an instance of Screen1.

class Screen1 {
    msg = "Hello"
    method1(arg: string): string {
        return this.msg;
    }

    method2 = (arg: string): string => {
        return this.msg;
    };
}

var v = new Screen1();
var fn = v.method1;
fn(""); // returns undefined
var fn2 = v.method2;
fn2(""); // returns "Hello"

In addition, there is a performance consideration. Due to normal functions being assigned to the prototype and created only once, they are more efficient. On the other hand, arrow functions need to capture this for each instance of the class, which can pose a problem when instantiating multiple objects.

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

What is the best way to retrieve the value of the hidden fields once the radio button has been selected?

I am currently attempting to retrieve the value of the hidden input fields each time a radio button is clicked. The code provided shows a single div structure, but there are multiple divs with the same structure. While I have been able to successfully ca ...

What steps can be taken to stop clients from sending an OPTION request prior to each GET?

Is there a way to deactivate the behavior of the client performing an OPTIONS request before every GET request? ...

Choose an element from within a variable that holds HTML code

I have a specific div element that I need to select and transfer to a new HTML file in order to convert it into a PDF. The issue I'm facing is related to using AJAX in my code, which includes various tabs as part of a management system. Just to prov ...

Unable to access class instance from event handler in Angular 2 and Typescript

In the scenario I'm working on, I need to dynamically add multiple instances of a child component to a template. Each of these child components emits a 'select' event, and each one requires a different event handler within the parent compone ...

Click on the button without any reaction

I'm having trouble with the button. When I click on the button with ng-click="goSearchTitle()", nothing happens. Any idea why it's not working? <body ng-app="myapp"> <div ng-contoller="searchbyTitle"> <h3>Sea ...

Ensuring the validity of an HTML form upon the user clicking the

I am looking to implement form validation in HTML by triggering it on click and displaying an error message if any field is left empty. I tried achieving this using JavaScript. <script type="text/javascript"> $(document).ready(function () { ...

Binding an event to an Angular 2 component directly within its selector code

Looking at my Angular 2 component: import { Component, ElementRef, Renderer } from '@angular/core';; @Component({ selector: 'my-button', templateUrl: 'button.html' }) export class ButtonComponent { private text: string ...

NativeScript: TypeScript for Formatting Numbers

Being a beginner in NativeScript, I'm finding it difficult to find basic information through Google search. But now, I have a specific question: I have the number 1234567.89 stored in a variable, and I want to display it in a label with the format ...

Checkbox Event Restricts Access to a Single Class Variable

As a beginner in AngularJS (just diving in this week), I've encountered an issue with a checkbox input connected to an ng-change event. <input type="checkbox" ng-model="vm.hasCondoKey" ng-change="vm.onKeyCheckboxChange()" /> The ng-change even ...

Can you explain the distinction between admin.firestore.Timestamp.now() and admin.firestore.FieldValue.serverTimestamp()?

Learn more about the servertimestamp function in Firebase Firestore Explore how to use the now function in Firebase Firestore Timestamp I'm confused about the distinction between these two functions. Can someone clarify? Specifically, what advantag ...

Having trouble extracting primary color from image with Microsoft's Computer Vision

I've hit a roadblock with this dilemma that has been perplexing me for quite some time now. My goal is to determine the dominant color of an image using Microsoft's Computer Vision service. A snippet of my code can be seen below: import {VisualFe ...

Stop receiving updates from an observable once you navigate away from an Onsen UI page

I am facing an issue with my Angular 2+ app that utilizes Onsen UI. I have set up some components as pages and I am using the ons-navigator to switch between them. The problem arises when I subscribe to an observable in an ons-page and the user navigates ...

Geocode promise left unattended

After reviewing my code, I discovered that it is executing too quickly for use in the Angular template. Here is an excerpt of the problematic code: this.dataService.getSomeData().subscribe(async (res) => { this.historyList = res; this.historyList.fo ...

Why does Rollup insist on treating my dependency's TypeScript code as if it were written in JavaScript?

I've included an example code snippet here: https://github.com/thejohnfreeman/bugs/commit/b4ff15a670691ada024589693d22f4fd0abae08d The module called parent is primarily composed of type declarations written in TypeScript. The source entrypoint for Ty ...

Inspecting a union type with a TypeScript property validation

I have defined a union of two types in my code. Here are the definitions: type Generic = { subtype: undefined, user: string, text: string } type Other = { subtype:'message', text: string } type Message = Generic | Other; Within my co ...

Displaying content in Bootstrap 5 modal with jQuery may cause a delay in the appearance of a centered spinner before the content loads

In my Bootstrap 5 modal, I have implemented specific functionality in jQuery where a centered spinner is supposed to show up in the modal before loading the content. You can see a live example of this here. The issue I am facing is that the spinner takes ...

Utilizing key values to access an array and generate a list of items in React.js

This marks my initiation on Stack Overflow, and I extend an apology in advance for any lack of clarity in my explanation due to unfamiliarity with the platform. My current task involves creating a resume with a dynamic worklist feature on my website. The ...

Exploring the intricacies of mapping an Array of Arrays

I'm currently tackling a data manipulation project that involves iterating through an array of arrays and generating a single string containing all possible combinations found within these arrays. For instance: const array = [ [{id: 1}, {id: 2}], ...

Prevent editing one item in a dropdown list in Angular by setting it to read-only

If I have a dropdown menu with options like "WORK", "RELEASE", and "OPEN", how can I make the second option, "RELEASE", read-only while allowing "WORK" and "OPEN" to be selected? Here is a snippet of the template code: <form [formGroup]="form" ...

What is the most effective way to extract data that includes an array within it?

const flightList = [{ number: 343, from: "Singapore", to: "India", upgradeTypes: ["Economy to Premium Economy", "Economy to Business Class"] }, . { number: 363, from: "Chennai", to: "Sing ...