Is it possible to enhance an external class with a non-static method using prototypes?

Is it possible to use prototypes to add a function for a class instance?

allowing me to access this or __proto__ keyword inside my method, like so:

class PersonClass {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  sayHello() {
    console.log(`hello, my name is ${this.name} and I'm a ${this.type}`);
  }
}

PersonClass.prototype.type = "human";
PersonClass.prototype.PrintType = () => {
  console.log(`I'm a ${PersonClass.prototype.type}`);
};

const aria = new PersonClass("Ned Stark");
aria.sayHello();
aria.PrintType();

This code works as expected, but I want to add something like

PersonClass.prototype.SayHello2 = () => {
  console.log(this.name, caller.__proto__.name);
};

which currently does not work.

Is there a way to achieve this?

Answer №1

To access the desired properties, your SayHello2 function should be a regular function instead of an arrow function:

PersonClass.prototype.SayHello2 = function () {
  console.log(this.name, this.type);
};

This code snippet will output:

"Jon Snow", "human" 

Remember that you can also utilize the constructor property of an instance to access all attributes associated with your classes.

Answer №2

Here is a solution that should function correctly:

    CharacterClass.prototype.Greet = function() {
      console.log(this.alias);
    };

    arya.Greet(); // "Ned Stark"

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 could be causing the audio file not to be received from the front end React to the Python server?

Here is the React code snippet: import React ,{ ChangeEvent, useState } from "react" const FileUpload: React.FC = () => { const [selectedFile, setFile] = useState<File| null>(null); const HandleAudioChange = (event:ChangeE ...

Using Google-Prettify with AngularJS

I have been attempting to implement Google Prettify in my AngularJS project. It seems to be functioning correctly on the main page, but once I navigate to another route using Angular (after ng-view), it stops working properly. You can check out the plunker ...

What are the best practices for implementing media queries in Next.js 13.4?

My media queries are not working in my next.js project. Here is what I have tried so far: I added my queries in "styles.module.css" and "global.css" and imported them in layout.js I included the viewport meta tag under a Head tag in layout.js This is how ...

Adjust grading system based on user interaction with JavaScript

I am currently working on a grading system for a website and I am attempting to modify the interpretation of grades when a column is clicked. Specifically, I am looking to convert Average (%) to Letters to 4.0 Grade Average. To achieve this, I am using Jqu ...

Use JavaScript to switch the h1 title when selecting an option from the dropdown menu

As a beginner in coding, I am struggling to find a solution using an if statement for this particular problem. Although I can achieve the desired result with HTML code and options, this time I need to use arrays and an if function. My goal is to create a ...

When utilizing Rx.Observable with the pausable feature, the subscribe function is not executed

Note: In my current project, I am utilizing TypeScript along with RxJS version 2.5.3. My objective is to track idle click times on a screen for a duration of 5 seconds. var noClickStream = Rx.Observable.fromEvent<MouseEvent>($window.document, &apos ...

Custom input field in Material UI not communicating properly with Redux form

I am currently utilizing Material UI and React to implement a custom input field. While using redux form for form validation, I have encountered an issue where the onBlur and onFocus events are not being dispatched successfully. Interestingly, if I switch ...

Using AngularJS to refresh information stored in an array

My objective is to create a basic application that allows users to adjust their availability on weekdays. The code is functioning correctly as it retrieves data from the select box. However, I encounter an issue when trying to update Monday's data and ...

Repeatedly view the identical file on HTML

I'm currently working with the following HTML code: <input type="file" style="display: none" #file(change)="processImage($event)" /> <button type="button" class="btn" (click)="file.click()" Browse </button> When I select image1 fr ...

Tips on implementing a jQuery .load() function using an anchor tag within dynamic content

I am working on a search page where user input is taken from a form and then sent to a PHP file that makes a cURL call to an external server. The PHP file receives an array from the server, which it uses to display HTML in a "results" div on the original s ...

There was a glitch encountered while constructing (Verifying type validity) with Prisma

There was an issue in the node_modules/@prisma/client/runtime/library.d.ts file on line 1161, specifically error TS1005 where a '?' was expected. 1161 | select: infer S extends object; | ^ 1162 | } & R ...

Locate and modify a specific element within an array of objects

Currently, I am working with an array that looks like this: arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}]. However, I need to add a condition to the array. If ...

The optimal method for selecting a button from a group of buttons on a calculator using pure JavaScript

I have developed an HTML/CSS code inspired by the Mac/Apple calculator design. It features buttons organized in 5 rows using flexbox. You can view my code on this codepen: <div class="wrapper"> <div class="calheader"> ...

Utilizing a JSDoc comment from an external interface attribute

Currently, I am in the process of developing a React application. It is common to want the props of a child component to be directly connected to the state of a parent component. To achieve this, I have detailed the following instructions in the interface ...

Creating a form that utilizes both jQuery and PHP to send the results, now including the complete code for reference

Full code update included. Changing the question: What occurs when all questions are answered in endQuiz, resulting in a user score? A form is displayed for the user to complete and submit to a designated email address. However, upon completing the form a ...

Steps for updating text within an object in Angular

details = [ { event: "02/01/2019 - [Juan] - D - [Leo]", point: 72 }, { event: "02/01/2019 - [Carlo] - N - [Trish]", point: 92 } ]; I am attempting to modify the text within the titles that contain - N - or - D - The desired outcom ...

Tips for creating responsive elements with a z-index of 1 in CSS

I have implemented the code provided in a codepen tutorial, but I replaced the world map image with a USA map. However, the dots are not responsive due to the z-index=1 specified on them. I experimented with vh, vw, and percentages, yet when I resize my s ...

Changing over to the left hand coordinate systemUniquely converting to a

One of the challenges I am facing involves an application that loads a model. Upon receiving a server response, I am provided with information regarding the axis to use for the right and up orientation. The format in which this information is sent can be ...

Iterating over an object and inserting values into a JavaScript object using the ascending count as the identifier

Illustration: { Are you a coffee drinker?: yes, Do you like to exercise regularly?: no, How often do you eat out at restaurants?: 3 times a week, What is your favorite type of cuisine?: Italian } Results: {yes: 1, no: 1, 3 time ...

Determining when all $http requests have completed in AngularJS

After running multiple $http calls, I need to trigger an event only when all of them have been processed. Additionally, I must be informed if any call has failed along the way. Despite attempting solutions found on stackoverflow, such as using an intercept ...