What is the process for attaching a function to an object?

Here is the complete code:

export interface IButton {
  click: Function;
  settings?: IButtonSettings;
}

abstract class Button implements IButton {
  click() {}

}

 class ButtonReset extends Button {
    super()
 }

The component looks like this:

export class ButtonsComponent {
private message = "Alert Message";
constructor() {
  let button = new ButtonReset();
  button.click = this.showAlert;
  button.click(); // This should log the value of 'message'
}

public showAlert() {
  console.log(this.message);
 }

}

Why am I unable to bind the method showAlert() to an instance of new ButtonReset(); and then call it?

A simpler example:

class ClassA {
  public text = "text 1";
  public obj: any;
}

class ClassB {
 public text = "text";
   printText() {
      console.log(this.text);
   }

}

let instA = new ClassA();
let instB = new ClassB();

instA.obj = instB.printText;
instA.obj();

I want to access text instead of text 1

Answer №1

If you have an instance of A (let's refer to it as a) and want the method call to get to return that instance's list of items, you can use the bind function to create a bound function for b.get:

b.get = a.get.bind(a);

Here is a JavaScript example illustrating this:

class A {
    constructor() {
        this.items = [];
    }
    get() {
        return this.items;
    }
}
class B {
}

const a = new A();
const b = new B();
b.get = a.get.bind(a);
console.log(b.get()); // Outputs `[]`, derived from `a.items`

However, if you desire the behavior defined in A.prototype.get to be enforced on the b instance (in order to access b.items), you can do the following:

b.get = A.prototype.get;

Another JavaScript example showcasing this concept:

class A {
    constructor() {
        this.items = [];
    }
    get() {
        return this.items;
    }
}
class B {
    constructor() {
        this.items = 42;
    }
}

const b = new B();
b.get = A.prototype.get;
console.log(b.get()); // Result: `42`, referencing `b.items` being set as `42`


In both scenarios described above, it is essential to specify a type for b indicating that it now contains a method called get, similar to the following declaration:

interface BPlus extends B {
    get(): any;
}

You might also find it useful to assign a new identifier with that specific type in mind:

const bp = <BPlus>b;    // Not accurate yet...
bp.get = a.get.bind(a); // Now it is

(Check out the TypeScript playground for further details)

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

Having trouble extracting a list of matches using a Regular Expression?

const stringWithDate: string = "4/7/20 This is a date!"; const reg: RegExp = new RegExp("^(\d{1,2}\/\d{1,2}\/\d{1,2})").compile(); const exist: boolean = reg.test(stringWithDate) const matches: RegExpExecArray | null = reg.exec(str ...

Typescript tutorial: Implementing a 'lambda function call' for external method

The Issue Just recently diving into Typescript, I discovered that lambda functions are utilized to adjust the value of this. However, I find myself stuck on how to pass my view model's this into a function that calls another method that hasn't b ...

Incorporate Material Design Icons into your NPM Electron React application for sleek visuals

I am currently exploring how to incorporate Material Design Icons into an NPM Electron project with Webpack 4. The Google Github page suggests that the icons can be easily installed using npm install material-design-icons. However, based on this discussion ...

Creating Multiple Result Lists in MUI Autocomplete Based on Option Properties: A Step-by-Step Guide

I have a query about displaying results using the MUI Autocomplete component. I am looking to categorize the results into two separate lists placed side by side. Currently, I have a working searchbar with one list of results. However, I aim to segregate t ...

Can you explain the concept of BuildOptions in Sequelize?

Despite poring through the sequelize documentation and conducting extensive searches online, I have yet to come across a satisfactory answer: Why is BuildOptions necessary and what impact does it have on the created model? import { Sequelize, Model, Data ...

Introducing an extra 'pipe' in rxjs angular may result in generating errors

Encountering an unusual issue with Angular. The following code functions correctly: this.form.valueChanges .pipe( startWith(this.form.value), pairwise(), tap(() => console.log('aa')) ...

Issue with Material UI grid not rendering properly in TypeScript environment

I've been trying to replicate a grid from material-ui using React and Typescript. You can see a live demo here. I modified the example to work with Typescript, so my demo.tsx file looks like this: Code goes here... If you check out the live demo, y ...

React Typescript - Unexpected character ',' encountered at line 1005

Currently, I am utilizing Typescript within a React application that integrates with Graphql. Encountering an error: ',' expected.ts(1005) After researching possible solutions, most suggest that the issue might be due to using an outdated ve ...

Is there a way to make PrismaClient return DateTime fields as Unix timestamps rather than JavaScript date objects?

When utilizing the PrismaClient for database interaction, DateTime fields are returned as JavaScript Date objects instead of Unix timestamp numbers. Despite being stored as Unix timestamp numbers in the database itself, I require the dates to be retrieved ...

The issue with Angular 4 imports not refreshing in a .less file persists

Currently, I am in the process of developing a small Angular project that utilizes less for styling purposes. My intention is to separate the styling into distinct folders apart from the components and instead have a main import file - main.less. This fil ...

Could Typescript decorators be used as mixins?

In the process of developing a complex Angular2 application, I have created a base class that serves as the foundation for my components: export abstract class ReactiveComponent implements OnInit, OnDestroy, AfterViewInit { abstract ngOnInit(): void; ...

Issue with toggling in react js on mobile devices

Currently, I am working on making my design responsive. My approach involves displaying a basket when the div style is set to "block", and hiding it when the user browses on a mobile device by setting the display to "none". The user can then click on a but ...

Using ngFor in Angular to display the API response

I am having trouble displaying a JSON response in my web panel. When attempting to show the full response, everything works perfectly. However, when I try to use ngFor, I encounter the following errors in the browser: ERROR TypeError: Cannot read property ...

Discover the power of working with asynchronous values in objects using the latest @if syntax in Angular 17

Previously, we were able to chain multiple async operations using *ngIf directives in Angular. This allowed us to avoid repeating the async pipe in the template and instead reuse them as a single subscription. With the introduction of the new @if syntax in ...

Why do selected items in Ionic 3 ion-option not get deselected even after reloading or reinitializing the array

HTML File: <ion-item class="inputpsection" *ngIf="showDeptsec"> <ion-label floating class="fontsize12">Department</ion-label> <ion-select (ionChange)="showDepartmentChosen($event)" multiple="true" formControlName=" ...

extract objects from an array of objects based on a specified array

Within my JSON array, I have data structured like this: const data = [ { "uniqueId": 1233, "serviceTags": [ { "Id": 11602, "tagId": "FRRRR", "missingRequired&quo ...

Problems arising from the layout of the PrimeNG DataView component when used alongside Prime

I've been working with a PrimeNG DataView component that requires the use of PrimeFlex's flex grid CSS classes to set up the grid structure. One of their examples includes the following instructions: When in grid mode, the ng-template element ...

Do Prisma Migrations Require a Default Value?

I'm struggling with Prisma data modeling and have tried almost everything to resolve an error I keep getting. The error states that the table needs a default value even though I have already assigned it an ID. I attempted to remove the relation name, ...

Typescript: The art of selectively exporting specific types

As I develop a Typescript component library, the API consists of two named exports: the component itself and a helper function to create an object for passing as a prop. The process is straightforward. For this library, I utilize an index.ts file as the m ...

Is there a way to automatically scroll to the bottom of a div when it first

Looking to enhance my application with a chat feature that automatically scrolls to the bottom of the chat page to display the latest messages. Utilizing VueJs: <template> <div id="app"> <div class="comments" ...