Expanding a class functionality by incorporating a method through .prototype

My goal is to define a class called "User" and then add a method to the class using the "prototype" keyword. I want the method "who_auto" to be accessible to all future instances of "User".

When testing this code in JSFiddle, I encountered the error message: "Uncaught TypeError: pp.who_auto is not a function"

Here's the revised code:

class User {
  constructor(name) {
    this.name = name;
    this.chatroom = null;
  }

  who() {
    return `I am ${this.name}`;
  }
}

User.prototype = {
  who_auto: function() {
    console.log(`
  Hello, I am ${this.name}
  `);
  }
}
const pp = new User('peter parker');
console.log(pp);
console.log(pp.who());

pp.who_auto();

Answer №1

You mistakenly overwrote the prototype instead of simply adding a property to it. The corrected code is shown below.

class User {
  constructor(name) {
    this.name = name;
    this.chatroom = null;
  }

  who() {
    return `I am ${this.name}`;
  }
}

User.prototype.who_auto = function() {
  console.log(`Hello, I am ${this.name}`);
}

const pp = new User('peter parker');
console.log(pp);
console.log(pp.who());

pp.who_auto();

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

HTML5 Audio using AudioJS may not function reliably when loaded remotely

I have been encountering frustrating issues with loading audio tags for a while now. Despite spending nearly two weeks trying to solve the problems, every fix seems to create another one. My webpage includes an < audio > tag that utilizes audio.js to m ...

Leveraging Ajax with PlayFramework Results

As stated in the PlayFramework Document 2.0 and PlayFramework Document 2.1, it is known that Play can return various responses such as: Ok() badRequest() created() status() forbidden() internalServerError() TODO However, when trying to send a response wi ...

Explicitly employ undefined constants deliberately

So I am working on a project called WingStyle: https://github.com/IngwiePhoenix/WingStyle. It is still in the development phase, and I'm looking for ways to improve its functionality. One thing I want to address is the use of quotes. For example, whe ...

Leveraging Selenium for extracting data from a webpage containing JavaScript

I am trying to extract data from a Google Scholar page that has a 'show more' button. After researching, I found out that this page is not in HTML format but rather in JavaScript. There are different methods to scrape such pages and I attempted t ...

Why isn't my classList .add method working properly?

I've created a video slider background on my website, but I'm having trouble with the Javacript for video slider navigation. When I click on the button to change the video, nothing happens. The console is showing an error message that says "Canno ...

Utilizing a particular iteration of npm shrinkwrap for project dependencies

When deploying my node.js app to Appfog, I encountered a problem with their install script failing to parse npm-shrinkwrap.json. The current format of a dependency in shrinkwrap.json is as follows: "async": { "version": "0.2.10", "from": " ...

Having trouble getting Ajax post to function properly when using Contenteditable

After successfully implementing a <textarea> that can post content to the database without needing a button or page refresh, I decided to switch to an editable <div> for design reasons. I added the attribute contenteditable="true", but encounte ...

Accessing form objects in Typescript with AngularJS

I am currently working with AngularJS and Typescript. I have encountered an issue while trying to access the form object. Here is the HTML snippet: <form name="myForm" novalidate> <label>First Name</label> <input type="text" ...

Tips for automatically filling out a div class form:

I currently have an Autoresponder email form featured on my webpage. Here is a snippet of the code for the section where customers enter their email: <div id = "af-form-45" class = "af-form" > <div id = "af-body-45" class = "af-body af-standa ...

Learn the process of integrating VueJS with RequireJS

I am attempting to set up VueJS with RequireJS. Currently, I am using the following VueJS library: . Below is my configuration file for require: require.config({ baseUrl : "js", paths : { jquery : "libs/jquery-3.2.1.min", fullcalendar : "libs/ful ...

Is there a way to prevent my token from being exposed when making an AJAX call?

When working on my HTML file, I encountered an issue with a Python Django URL integration where I need to pass a token to retrieve certain information. However, the problem is that my token is exposed when inspecting the page source in the HTML document. ...

JavaScript onclick event on an image element

I have a JavaScript function that shows images using CSS styles. <script type="text/javascript"> $(function () { $("div[style]").click(function() { $("#full-wrap-new").css("background-image", $(this).css("background-image")); }); }); ...

What is the best way to iterate over my JSON data using JavaScript in order to dynamically generate cards on my HTML page?

var data = [ { "name":"john", "description":"im 22", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c7d7e7f0c2b212d2520622f">[email protected]</a>" }, { "name":"jessie", ...

The never-ending cycle and memory overload that occur when using Angular's ngRoute

It seems like I may have hit a roadblock while attempting to get ng-view and ngRoute up and running. Everything appeared to be functioning correctly, but it looks like the entire process is caught in a loop. Just to provide some context, I am working with ...

Neglecting to review the CSS - embracing ejs layouts in Express

I am encountering an issue with the express ejs layouts where only the mainPage is able to read the CSS, while the other pages are unable to do so (even though the HTML reads it). Additionally, if I want to use another layout such as "layout2.ejs", what s ...

Infinite scrolling with a dynamic background

Hi there, I am working on my website and trying to create a smooth transition between sections similar to the one demonstrated here:. The challenge I'm facing is that the backgrounds of my sections cannot be fixed; they need to have background-attachm ...

Is there a way to determine if a React functional component has been displayed in the code?

Currently, I am working on implementing logging to track the time it takes for a functional component in React to render. My main challenge is determining when the rendering of the component is complete and visible to the user on the front end. I believe t ...

Control other inputs according to the chosen option

Here is the HTML code snippet: <fieldset> <label for="tipoPre">Select prize type:</label> <select id="tipoPre"><option value="Consumer Refund">Consumer Refund</option> <option value="Accumulated Prize Ref ...

The select2 ajax functionality encountered an error: Uncaught TypeError - Unable to access the 'context' property as it is undefined

Trying to make an AJAX request using the Select2 jQuery plugin. The query appears to be functioning properly, but the problem arises when ".context===undefined" is called on the "data" object: Uncaught TypeError: Cannot read property 'context' o ...

One should refrain from loading the API in Angular when there is no data present, by utilizing the global.getData method

Check out this code snippet: loadNextBatch() { console.log('scrolldown'); this.pageIndex = this.pageIndex + 1; this.global.getData(`/conditions/latest?start=${this.pageIndex}&length=${this.pageSize}`) .pipe(take(1)).subscr ...