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

The node.js server responds with undefined after an AJAX request

Currently, I am facing a challenge in retrieving and accessing a string that is produced by a serverside function in Node.js. function createString () { do something ... console.log(finalString); return finalString; }; To fetch this string f ...

How can I convert a UTC time field from MySQL into JavaScript?

I'm struggling to pinpoint the error in my date/time difference calculations. It seems to be related to timezone variations, but I can't figure out exactly where the problem lies. Below are all the components involved - can you help me identify t ...

The ng-show directive seems to be malfunctioning when used with UnderscoreJS's _.isNull function, but it functions properly when comparing

When using an ng-show directive on an element, I noticed that the UnderscoreJS helper function _.isNull behaves differently than the standard === operator. For example, when checking if newJobWorkPercentage is null: <div class="form-group" ng-show="ne ...

Timing measurements in JavaScript: comparing Date.now with process.hrtime

I need to regularly calculate the time difference between specific time intervals. When it comes to performance, which method is more efficient: Date.now or process.hrtime? C:\Windows\system32>node > process.hrtime() [ 70350, 524700467 ] ...

Calculate the sum in real-time using JavaScript

How can I dynamically compute the sum of subtotals without encountering the following error? document.getElementById("item_subtotal[" + cnt + "]") is null Below is my JavaScript code: function calculateTotalAll(numitems) { var cnt = 1; var tot ...

The "useState" React Hook is restricted from being used in a class component. To utilize React Hooks, they can only be invoked within a React function component or a custom React Hook function

I am relatively new to React frontend development and I am currently working on adding a temporary drawer to my Material-UI NavBar. Here is the code snippet where I added the drawer: class Navbar extends Component { render() { const { authentic ...

Numerous entities in motion, each adorned with its own accompanying text

I have been experimenting with the interactive cubes and recently implemented a click function that directs to specific links. Now, I am interested in assigning distinct text to each cube as a material when rendered. Currently, I am using a single materi ...

HTML code now launches in the existing electron window rather than opening a new window

<html> <head> <title></title> </head> <input type="button" name="new" id="newmon" value="new"> <button onclick="open1()">monitor 1</button&g ...

Guide on how to showcase JSON data using vanilla JavaScript within the Laravel framework

As a beginner in Laravel, I am looking to pass JSON data from my controller using vanilla JavaScript to my view blade. However, I am unsure of the steps to accomplish this. Below is an example of my controller: public function index(Request $request) { ...

What are the steps to enable ajax communication with a database for posting, retrieving, and removing data?

Is there a way to utilize ajax for posting, deleting, and getting data from a database? I am looking to post content and then be able to delete it through the following link: (this is part of an assignment) However, I must use /ajax/addrecord.php and /a ...

Guide to updating current rjs files to incorporate jQuery and json in Rails 3

Currently, in my Rails 3 application, I am using rjs to render partials in my controllers. An example of this is when saving a new item to a table, the table gets refreshed: respond_to do |format| format.js { render :update do |page| ...

Is there a way to delay rendering the html until all the content has been fully downloaded?

Whenever I visit my webpage, I notice that the content starts loading without the animation applied to it. It seems like the CSS hasn't finished downloading yet. To solve this issue, I added a preloading bar overlay to signal that the content is still ...

Removing duplicate values in Vue after sorting

Explore <div v-for="todo in sortedArray"> <b-button block pill variant="outline-info" id="fetchButtonGap" v-model:value="todo.items[0].arrivalTime"> {{fromMilTime(todo.items[0].arrivalTime)}} < ...

Steps for recreating a Jquery Mobile form element with the same name after destroying it

As I delve into Jquery Mobile, I encounter a scenario where I must dynamically generate form fields (select, input, etc) using the following approach: $fieldInput = $('<input type="text" name="' + fieldName + '" />'); Initially, ...

Update a JavaScript variable with fresh information and then execute JSON parsing

I have implemented this code to display a Verite Timeline on my webpage: <div id="timeline-embed"></div> <script type="text/javascript"> var timeline_config = { width: "100%", height: "100%", debu ...

What is the best way to transfer an integer from my main application to a separate JavaScript file?

Currently, I am developing a complex code using React Bootstrap and focusing on creating a Dropdown list that fetches data from the backend database. <Dropdown> <Dropdown.Toggle variant="success" id="dropdown-basic"></D ...

Why is my React component not updating after changing the state using Set State?

Uncovering the elusive problem seems impossible. Despite state changes, the component remains unrerendered. Here's the code: export const InterestsPupup: React.FC = ({interests, title, buttonText}) => { const [activeItems, setActiveItems] = useSt ...

Is there a way to display a button and text upon hovering over an image without using JQuery?

On my current WordPress project, I am faced with the task of creating a gallery that displays text and a button when users hover over an image. I have attempted to use a:hover but have only been able to make limited modifications. Can anyone provide guid ...

When the application is converted into static files, the dynamic routes fail to function properly

I have a website that is statically exported but has dynamic routes. During development, the site works fine. However, when I build and export it, then serve the static files using serve, an issue arises. If you go to the site root and click on a link th ...

Using Jquery to monitor input field modifications following a background ajax refresh

I am facing a challenge with my two JQuery functions. The first function executes an ajax load based on the user's selection from a drop-down menu, and then updates an input field according to the data returned. This function is working correctly. // ...