The most effective method for acquiring an object through inheritance

I'm seeking advice on the best practice for adding behavior to an object received as a JSON object.

I have REST services that allow me to define a sort of state machine.

The API defines a /sessions resources. When creating a session via POST /sessions/:id, I receive a JSON object in my controller:

var session = {
   "id": "",
   "steps": [ ... ]
}

I would like this object to inherit some behavior:

var baseSession = {
  "nextStep": function() {... },
  "getCurrentStep": function() { ...}
}

My initial thought was to do this:

session.__proto__ = baseSession;

However, using __proto__ doesn't seem like the right approach. Another option would be to duplicate every property in a new object:

function copyOwnProperyTo(origin, obj) {
     Object.keys(origin).forEach(function(prop) {
        obj[prop] = origin[prop];

    });
}
var newSession = Object.create(baseSession);
copyOwnProperyTo(session, newSession);

This solution works but seems a bit heavy to me. Any other suggestions?

Answer №1

The recommended ES6 approach involves merging Object.assign with Object.create:

const session = Object.assign(Object.create(baseSession), {
   "id": "",
   "steps": […]
});

Alternatively, you have the option to implement your own method for copying objects instead of relying on Object.assign.

Another method to consider is Object.setPrototypeOf, which can be utilized like so:

const session = Object.setPrototypeOf({
   "id": "",
   "steps": […]
}, baseSession);

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

Is it possible to invoke a helper function by passing a string as its name in JavaScript?

I'm encountering a certain issue. Here is what I am attempting: Is it possible to accomplish this: var action = 'toUpperCase()'; 'abcd'.action; //output ===> ABCD The user can input either uppercase or lowercase function ...

Having trouble deleting the value and deselecting the checkbox item?

Feeling a bit confused about a coding issue I'm facing. The problem lies in the categories listed in my database, which I fetched and used to create a post. Now, I'm attempting to edit that post. The categories are in checkbox format, where check ...

Display upon hovering, conceal with a button located within a popup container

There seems to be an issue with the code below. Even though it works perfectly in jsfiddle, it breaks in my Chrome and other browsers right after displaying the ".popup" div. Can anyone point out what I might be doing wrong? I found similar code on this si ...

Failure to display React component on screen

I have developed a React microfrontend application consisting of two sub-apps rendered through the container/ project. Both sub-apps render perfectly in isolation on localhost:8083. However, when attempting to view them via localhost:8080/dashboard, I am p ...

The powerful combination of Ajax and Django creates a dynamic Like button

Encountering difficulties while trying to implement a basic like button feature. Despite following various tutorials, clicking on the Like button does not yield any action. See below: models.py class Comentario (models.Model): titulo = models.CharFie ...

Unable to resolve an unresolved issue with a jquery or javascript bug

I am currently facing some issues with my jQuery code in both Firebug and Chrome's developer tools. Any assistance would be greatly appreciated. Kindly make the necessary updates in the provided fiddle. Please follow this link to access the fiddle: ...

How can the 'Read more' feature be modified to impact multiple boxes? (Using jQuery, JS, and CSS)

I am trying to add a 'Read more' feature on my friend's website. I was able to achieve the desired effect, but when I tried to adjust the alignment of the box, it affected the 'Read more' feature. Original design: https://codepen. ...

Providing arguments to mocha while executing through npm

I'm currently setting up nyc/mocha for my project and I need to pass the --exit option to mocha when running it with or without nyc. Below is a snippet from my package.json file: "scripts": { "start": "node ./app", "test": "./node_modules/.b ...

I need to transmit user data, excluding the password, from the express server along with a jwt token

As I develop a MERN stack ecommerce application, I am looking to send all user information along with a jwt token, but I want to exclude the password. I understand how to handle the token part and send the user data through res.json. However, I'm unsu ...

What is the reason for the retrieval of jquery-3.5.1.min.js through the request.params.id expression?

For my school project, I am using Express.js with TypeScript to create a simple app. This router is used for the edit page of a contact list we are developing. It displays the ID of the current contact being edited in the search bar. The problem arises whe ...

How to handle an unexpected keyword 'true' error when using the `useState` hook in React?

Trying to set the open prop of the MUIDrawer component to true on user click is causing an error stating "Unexpected keyword 'true'" import React, { useState } from "react"; import { withRouter } from "react-router-dom"; impo ...

Encountering a problem while attempting to parse a JSON object in Java using the

I am struggling with a JSON string that looks like this: String result={[{"id":"2","fullname":"Course 1"},{"id":"3","fullname":"Course 2"}]} In my Java code, I attempted to decode the JSON string using the following snippet: public class Courses { publ ...

Trouble transferring $rootScope.currentUser between AngularJS profile and settings page

I am in the process of setting up a site using Angular, Express, Node, and Passport. Currently, I am configuring Angular to monitor the $rootScope.currentUser variable with the following code: app.run(function ($rootScope, $location, Auth) { // Watch ...

Interpreting an undefined HTTP GET request within a Node.js server

I am encountering an issue within my Node.js application. When I send an http get request through an ajax call on the client-side, the server-side does not recognize the request data and returns an "undefined" error message. This problem is puzzling to me ...

The CSS_MODULES encountered a module build error when utilizing the extract-text-webpack-plugin

While processing CSS with CSS modules in a production environment, I encounter an error, but everything works fine in the development environment. Here is the configuration for webpack.base.js: const path = require("path") const webpack = require("webpac ...

A guide to displaying dropdown values above a modal

I have encountered an issue while using a dropdown inside a modal window. The problem is that not all the dropdown values are visible, as the overflow part gets hidden. I am looking for a solution to keep the dropdown value at the top and prevent it from b ...

The logo image dynamically switches as the user scrolls through various colored sections

Looking to create a feature that changes the logo image as users scroll through different colored sections. Specifically, switching between dark and light themes. a) How can we determine if the section the user is currently on has a dark or light theme? b ...

Implement a unique feature for specific days using jQuery UI Datepicker with a customized class

Looking to highlight a range of days horizontally in jQuery UI Datepicker with the multiselect plugin. To achieve this, I am utilizing the :before and :after pseudoelements of the a tags. .ui-state-highlight a:before, .ui-state-highlight a:after { con ...

The jQuery load() method may not load all elements

I've been struggling with a query issue for quite some time now. I have a Content Management System that I want to integrate into my website, but unfortunately, I am unable to use PHP includes. As an alternative, I decided to utilize jQuery instead. D ...

Toggle the image and update the corresponding value in the MySQL database upon clicking

Looking to implement a feature that allows users to bookmark pages in my PHP application using JavaScript. The concept involves having a list of items, each accompanied by an image (potentially an empty star). When a user clicks on the image, it will upda ...