What is the process for incorporating a new method into an object that already exists?

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  sayName() {
    alert(this.name);
  }
}

// Create three instances of the Person class with some made-up data
const p1 = new Person('Alice', 25);
const p2 = new Person('Bob', 30);
const p3 = new Person('Charlie', 28);

// The method `sayName` has been added to the Person class using ES6 syntax.

I'm still learning JavaScript and figuring out how to work with classes. I find it easier to add new properties than new functions to a class. Practice makes perfect!

Answer №1

Include the function in the Person prototype inheritance.

Person.prototype.displayName = function() {
    return console.log(this.name);
};

Answer №2

function Cat(name, age) {
  this.name = name;
  this.age = age;
};

Cat.prototype.meow = function () {
 alert("Meow! My name is " + this.name);
}

var cat1 = new Cat('Whiskers', 5);

cat1.meow() 

You can create methods using prototype

Cat.prototype.purr = function() { ... }

Answer №3

Person.prototype.displayName = function() { 
  alert(this.name)
}

By adding a prototype function to the Person class, every individual within the class can utilize this function.

Answer №4

To incorporate a method into an object, one technique is by utilizing prototyping. By using the syntax

myObject.prototype.myMethod = function(){ ... }
, you can easily add a method to an object.

Person.prototype.sayName = function(){
    console.log(this.name);
}

Alternatively, you can directly include the method during the creation of the Person. However, keep in mind that this approach will result in the method being duplicated for each instance:

var Person = function(name, age) {
  this.name = name;
  this.age = age;

  this.sayName = function() {
      console.log(this.name);
  }
};

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 process of mapping an array of object IDs in order to retrieve the corresponding objects associated with each ID

I currently have a specific collection that stores IDs referencing objects in a separate schema. If I'm working with an array containing these IDs, what is the best way to iterate through and retrieve the corresponding object? Although I've mad ...

I'm a beginner when it comes to Android WebView and incorporating JavaScript into my projects

Struggling to make my Android app work with JavaScript, even though I've enabled it. Despite all the research I've done suggesting it should work, it's not. Any assistance would be greatly appreciated. Below is my Java code: protected ...

Incorporating a specific time to a JavaScript date object

In my Angular application, I am facing an issue with adding a time to a date. The appointmentDate from the date picker returns a JavaScript date while the appointmentTime is selected from a dropdown with options like "8:00", "8:30", "9:00", etc. I'm ...

Why isn't the function in my React child component passing its parameters to the parent component's function as expected?

In the parent: const [currentPinPosition, setCurrentPinPosition] = React.useState({ lat: 0 , lng: 0 }); const updateCurrentPinPos = (position) => { console.log(position); setCurrentPinPosition({ lat: position.lat, lng: position.lng }); }; / ...

Disappearing act: The vanishing act of the Bootstrap 4 Smart Scroll Mobile

Utilizing the Smart Scroll feature from in Bootstrap has been successful on desktop, but issues arise on mobile devices. When scrolling down and returning to the top, the navbar experiences glitches by hiding again. Attempting solutions from Bootstrap 4 S ...

Utilizing the zIndex property on a map label does not produce any impact when combined with a GeoJSON layer

Utilizing the Google map label tool, I am trying to showcase certain property from GeoJSON data on a GeoJSON layer. However, the issue arises as the layer has a dark color and the label is appearing blurry behind the GeoJSON data layer. Despite attempting ...

Developing an npm module that is compatible with both web browsers and Node.js

Currently, I am in the process of developing an npm package that will cater to both web apps and other node modules. If my focus was solely on browsers, I would simply assign window.myExport = myExport; as a direct solution (unless there is a more contemp ...

ng-class not functioning properly when invoked

In my controller, I have the following function: $scope.menus = {}; $http.get('web/core/components/home/nav.json').success(function (data) { $scope.menus = data; $scope.validaMenu(); }).error(function () { console.log('ERRO') }); ...

Initiating an AJAX request to a JSP file

Attempting to make an ajax call to a jsp page as shown below: $(document).ready(function () { $('#photo').photobooth().on("image", function (event, dataUrl) { alert(dataUrl); //alert($('#mygroupuserid')); ...

Obtain the URL link from Unsplash where the picture is sourced

As I work on a website, I incorporate a link () to display a random photo. However, the photo refreshes periodically and upon loading the site, all that is visible is this default link: . Is there a method to extract the actual source like so: "". Althou ...

Toggle textboxes using jQuery depending on the radio button choice

I'm trying to make specific textboxes appear when a particular radio button is clicked on my form, but I want them to remain hidden otherwise. Here's an example of what I've implemented: HTML: Radio buttons: <p>Show textboxes<inpu ...

Parsing JSON sub items in Android application using Java

Here is a snippet of my PHP file: <?php $myObj = array( "name"=>"John" , "age"=>"30" , "post"=>[ "title"=>"What is WordPress" , "excerpt"=>"WordPress is a popular blogging platform" , ...

The class functions perfectly under regular circumstances but ceases to operate once it is initialized

I'm currently developing a bluetooth remote in React Native. The issue I am facing is that my BLE class works perfectly on its own, but certain sections of code seem to malfunction when implemented within another class. import BLE from './Core/BL ...

Sending an array of dictionary objects to a JavaScript function

I have a situation where I need to pass a large amount of data stored in an NSArray containing NSDictionary objects to a JavaScript function using a webview and the method: - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script My inquir ...

Issue encountered when trying to attach a hover event to the items in a comb

Currently, I am facing a specific situation. The requirement is to display a custom tooltip when the mouse hovers over the combobox items (specifically the "option" tag). Initially, my solution involved using the title tag. While this method worked effecti ...

Tips for sending an icon as a prop in React components

I'm struggling to implement an icon as a prop while using props for "optionText" and "optionIcon". The optionText is working fine, but I'm facing issues with the OptionIcon. File where I'm creating props import Icon from ...

How can I eliminate the default background of Mui tooltip and personalize it in react?

Below is an example of how to customize a nested tooltip within a default background tooltip in MUI. The challenge here is to remove the grey border in the customized tooltip and have only a white background with black text. Check out the code snippet be ...

Troubleshooting issues with the delete functionality in a NodeJS CRUD API

I've been struggling to implement the Delete functionality in my nodejs CRUD API for the past couple of days, but I just can't seem to get it right. As I'm still learning, there might be a small detail that I'm overlooking causing this ...

Adding rows to a Datatable using an object array in rows.add()

Attempting to refresh my current Datatable by fetching new data using an Ajax function. Despite trying various solutions from other sources, the table does not update as expected. The function being used is shown below: $.ajax({ url: "<?php echo s ...

Page refreshing in Angular 5 consistently redirects to the home page instead of staying on the current page

I am experiencing an issue with the navigation on my application. When I navigate to routes like getEmp-by-id or page-not-found and hit refresh, the application automatically redirects me back to app-home. However, I would like it to stay on the same pag ...