Bind the prototype to the JavaScript object

Consider this scenario where I have JSON data containing person objects.

[
  {
     "name": "Alice",
     "age": 28,
  },
  {
     "name": "Bob",
     "age": 33
  }
]

Upon parsing, an array with two JavaScript objects is obtained. Suppose I want to add a method called introduce to these objects, which would look something like this:

function introduce() {
  return "My name is " + this.name + " and I am " + this.age + " years old.";
}

One way to achieve this would be iterating over the objects and calling:

person.constructor.prototype.introduce = introduce

However, this approach will make the introduce function accessible to all JavaScript objects, not just the intended ones.

Alternatively, manually attaching the function to each object can be done, but in case of adding more functions later, it would require iterating over all objects again.

Ideally, having a prototype that can be fitted with the introduce method and then connected to all person objects would be preferred. This way, if the prototype is extended in the future, the added functions will also be available to the person objects.

The query now arises: how can this be achieved?

Answer №1

My recommendation is to establish a new class:

JSBin

var Individual = (function () {
    function Individual(person) {
        this.person = person;
        this.name = person.name;
        this.age = person.age;
    }
    Individual.prototype.introduction = function () {
        return "I go by the name of " + this.name + " and I am " + this.age + " years old.";
    };
    return Individual;
})();

Answer №2

Your query seems a bit unclear, but it appears that you are looking to create a separate "person" class instead of just a regular object:

function Person(obj) {
    this.name = obj.name;
};

Person.prototype.introduce = function() {
    return console.log('Hello, my name is '+this.name);
};

var personA = new Person({ name:'Alice' });
var personB = new Person({ name:'Bob' });

personA.introduce();  // "Hello, my name is Alice"
personB.introduce();  // "Hello, my name is Bob"

Answer №3

Create a basic Individual class:

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

For example, here is an array of individuals:

var individuals = [
  {
     "name": "Eve",
     "age": 25,
  },
  {
     "name": "Dan",
     "age": 40
  }
];

Transform the individuals array into an array of Individual:

individuals = individuals.map(function(i){
    return new Individual(i.name,i.age)
});

Include the following method to the prototype:

Individual.prototype.greet = greet

Answer №4

If needed, you have the option to utilize either the outdated deprecated __proto__ property or the more modern ES6 method Object.setPrototypeOf. Keep in mind that it is not recommended to modify an object's prototype directly (as noted here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto), although there are cases where it may be justified.

var you = { name: "Niels B." }
you.__proto__ = { hello: function () { console.log(this.name) } }
you.hello()

In relation to your specific issue:

function Person() {}
Person.prototype = {
  introduce: function () {
    return "My name is " + this.name + " and I am " + this.age + " years old.";
  }
}

Then for each person:

person.__proto__ = Person.prototype;
// or
Object.setPrototypeOf(person, Person.prototype);

For further performance comparisons, refer to this JSPerf: http://jsperf.com/parse-json-into-an-object-and-assign-a-prototype

Additional discussion can be found here: https://groups.google.com/forum/#!topic/ringojs/PxS1O5jMx-8

Answer №5

Implement a person class using the Person.prototype method:

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

function introduction() {
  return "Hi, I'm " + this.name + " and I am " + this.age + " years old.";
}

Person.prototype.introduction = introduction;

person1 = new Person ("Alice", 25);
person1.introduction();

Answer №6

One way to organize these individuals is by creating a structured format.

let Person = function Person(info){
 this.name = info.name;
 this.age = info.age;
};
Person.constructor = Person;

Next, you can iterate through to generate the individuals.

let individuals = [];
for(let i = 0; i < data.length; i++){
 individuals.push(new Person(data[i]));
}

Once the individuals have been created, they may need to introduce themselves. You could extend the functionalities of the Person "class".

Person.prototype.introduction = function() {
  return "Greetings! My name is " + this.name + ", and I am " + age + ".";
}

This will enable them to utilize the introduction function:

for(let i = 0; i < individuals.length; i++){
 console.log(individuals[i].introduction());
}

Answer №7

To avoid reconstructing every time, you can consider the following approach:

let people =[
  {
     "name": "Alice",
     "age": 28,
  },
  {
     "name": "Bob",
     "age": 33
  }
],
i=-1,len=people.length,tmp
,proto={
  sayName: function(){
    console.log("from sayname",this.data.name);
  }
};
while(++i<len){
  tmp=Object.create(proto);
  tmp.data=people[i];
  people[i]=tmp;
}
people[0].sayName();
proto.sayName=function(){console.log("changed it");};
people[1].sayName();

If your JSON objects have a lot of members, this method could potentially save you from duplicating them in your constructor function. However, the performance benefits are uncertain.

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

Implementing proper data return in MVC4 through an Ajax call

When using ajax to call an action in a controller, the code may result like this: $.ajax({ type: "POST", url: "getUserInfo.json", data: "", success: function (data) { if (data.resultInfo.resu ...

Utilizing Selenium and Python to extract data from JavaScript tables via web scraping

I've come across numerous articles about Web Scraping, but I'm still struggling to figure out how to locate specific elements on a website. The site where I want to scrape the tables can be found here: My target tables are: "TB01," "TB02," "TB0 ...

Executing function statement

I'm currently learning about React hooks, and I have a question regarding the behavior of two function expressions within different useEffect hooks. In one case, the function expression named timerId in the first useEffect is invoked automatically wit ...

The package-lock file may vary depending on the npm version being used

I am experimenting with a new typescript react app that was created using CRA. I am running @6.4.1 on one PC and an older version on another. Interestingly, the newer version installs dependencies with an older version instead of the expected new one. ...

Node and Express Fundamentals: Delivering Static Resources

const express = require('express'); const app = express(); app.use(express.static('public')); I've been attempting to complete the "Basic Node and Express: Serve Static Assets" challenge on freecodecamp, but it keeps showing as " ...

Developing a specialized command-line application for currency conversion is my current project

Currently, I am working on developing a command-line application for currency exchange. I have created an interface to define the structure of an object array that will store the keys and values of currency names along with their current values in the inte ...

What is the cost associated with using the require() function in an Express.js application?

I have a web application built with Express.js that serves one of my domains. The structure of the app.js file is as follows: var express = require('express'); var app = express(); // and so on… To incorporate one of my custom functions in t ...

Any ideas on how I can adjust this basic JSON to avoid triggering the "Circular structure to JSON" error?

Learning Journey I am currently teaching myself JavaScript and exploring JSON along the way. My current project involves developing a JavaScript WebScraper where I plan to store my results in JSON format. While I am aware of other methods like using data ...

Angular SPA Routing for .Net Core 2.0

Having recently created a new Angular SPA project using the .Net core 2.0 SPA templates, I find myself facing some challenges as a newcomer to Angular/Typescript and HMR. While most functionalities were working smoothly at first, I noticed a peculiar issu ...

What could be the reason for PhantomJS getting stuck when jQuery is invoked?

Currently, I am using PhantomJS 2.0.0 on a Mac OS X Yosemite: $ phantomjs --version 2.0.0 The script I have attached below seems to get stuck at the line where it calls $('h1').size(): system = require('system'); function usage() { ...

Converting a string to null with PHP's json_encode

I'm currently troubleshooting a problem with a PHP script I've been working on. The script utilizes the phpseclib library to encrypt a password using a public RSA key provided by an ASP.NET application. Everything appears to be functioning proper ...

Updating the $location variable from the $rootScope perspective

I am facing an issue with my web app which is built using AngularJS. I have two functions in my code - one declared on the $rootScope and the other on the $scope. The code snippets are shown below: app.js app.run(function ($rootScope, $location) { $roo ...

Revamp the Design Layout of a Drag-and-Drop Tool

After experimenting with a drag and drop feature using jQuery, I discovered the following useful code snippet. Here's how it functions: $( "#sortable1, #sortable2" ).sortable({ connectWith: ".connectedSortable" }).disableSelection(); #so ...

What is the best way to transfer data from a div tag to an li tag using JavaScript?

https://i.stack.imgur.com/se2qk.pngI am attempting to change the div tag content to li tag. Here is a snippet of the code from inspect for reference. I need to remove the div tag with the "domTitle" class. <li style="display: inline;" id="list_name"> ...

Passing asynchronous data from method1 to method2 without impacting the functionality of the script responsible for fetching the asynchronous data in method1

When working with TypeScript, I encountered an issue while trying to invoke an external script called SPCalendarPro within a private method that asynchronously fetches data. The script is invoked in the following manner: private _getSPCalendarPro() { con ...

Turn off the background when the automatic popup box appears

I have implemented a popup box that automatically appears after 5 seconds when the site is loaded. However, if I click outside of the popup box, it closes. I want to disable the background when the popup box is displayed. If I remove the two lines of code ...

GruntJS is piecing together a JSON file using a helper to break it down into

Currently, I am looking to implement a custom helper that will allow me to parse an entire JSON file into a partial. While the technique from this site has been helpful: Parsing Json data into partial I have found that it works well for parsing individua ...

Looking for non-case-sensitive letters in a text input field

Having trouble with case-insensitive search using jquery? The search option seems to be working fine, but there's an issue with uppercase and lowercase letters in the content. Check out my full code on jsfiddle where if I search for "senthil" it doesn ...

Encountering an issue with Node JS request and cheerio while parsing an HTML page

Greetings all, I am currently attempting to parse a website using Node.js (utilizing request and cheerio). The issue I am encountering is that I am trying to extract the href from the site, but I can only find it within the site's window. Unfortunatel ...

Transforming an interactive HTML webpage into React/JSX

Imagine a scenario where I have two files: example.html <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta charset="u ...