Ways to avoid the extension of object properties in JavaScript

I am in the process of sealing an object property.

My question is, if I use Object.seal(personObject), the specific object gets sealed and does not allow any configuration or extensions. However, when I do not mention it on personObject_2, it still allows extension or configuration.

Is there a way to apply this seal to prototypes? In other words, any class of type person should have to adhere to this seal. Is achieving such behavior possible?

"use strict";
var personModule=(function (module) {
   var  person=function (fname,lname) {
       Object.defineProperty(this,'firstName',{
          get:function () {
            return fname;
          }
          ,set:function (newValue) {
            fname=newValue;
         },
         configurable:true
       });

       Object.defineProperty(this,'lastName',{
         get:function () {
           return lname;
         }
         ,set:function (newValue) {
           lname=newValue;
         },
         configurable:true
       });

       Object.defineProperty(this,'fullName',{
         get:function () {
           return fname+lname;
         },
         configurable:true
       });

     }
     module.person=person;
     return module;
})(personModule || {});

var personObject=new personModule.person( "Raju","Rani");
console.log(personObject.fullName);
Object.seal(personObject);
//delete personObject.firstName;-->It throws error here

var personObject2=new personModule.person( "Shiva","Kumar");

delete personObject2.firstName;

console.log(personObject2.firstName);

Thanks

Answer №1

For those who do not want to include Object.seal in the constructor, here is an alternative Proxy version:

"use strict";
var personModule=(function (module) {
   var  person=function (fname,lname) {
   Object.defineProperty(this,'firstName',{
      get:function () {
        return fname;
      }
      ,set:function (newValue) {
        fname=newValue;
     },
     configurable:true
   });

   Object.defineProperty(this,'lastName',{
     get:function () {
       return lname;
     }
     ,set:function (newValue) {
       lname=newValue;
     },
     configurable:true
   });

   Object.defineProperty(this,'fullName',{
     get:function () {
       return fname+lname;
     },
     configurable:true
   });

 }
 module.person=new Proxy(person, {
     construct(target, args){
         args.unshift(null);
         let ctor = target.bind.apply(target, args);
         let result = new ctor();
         Object.seal(result);
         return result;
     }
 });
 return module;
})(personModule || {});

var personObject=new personModule.person( "Raju","Rani");
console.log(personObject.fullName);
Object.seal(personObject);
//delete personObject.firstName;-->It throws error here

var personObject2=new personModule.person( "Shiva","Kumar");

delete personObject2.firstName;

console.log(personObject2.firstName);

Answer №2

Have you ever experimented with immutable-js?

var userObject = new userModule.user("Rick", "Morty");

var sealedData = Immutable.Map(userObject);

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 timeAgo with jQuery (or a similar tool) to display the elapsed time since a user (client) accesses or updates a webpage

https://i.sstatic.net/Y7bzO.png Currently, the timer displayed always shows the actual time instead of phrases like "about a minute ago" or "5 minutes ago". I have tried different solutions without success. //timeago by jQuery (function timeAgo(selector) ...

Attempting to reposition a button through JavaScript functions

Need help with a school project: When the user clicks the initial login button, it should be removed and replaced by a new button that descends 100 pixels over a 2-second period. I'm looking for a more efficient way to achieve this, any assistance wou ...

JavaScript pop-up purchase tooltips from MenuCool

I am relatively new to the world of web design and programming. I am putting in a lot of effort to learn as much as possible, but I am encountering difficulties with the tooltip JavaScript that I incorporated into my website Click here to visit my website ...

You are unable to declare objects within an object of a Class in JavaScript

class B{ item = {}; item.name = "example"; } let b = new B() What is the reason behind not being able to define an object and add a property inside a class like this? ...

Challenge with delayed function execution in AngularJS

In my Angular application, I am encountering a problem in the following scenario. There are three crucial files: MainCtrl.js Upon loading the application, the init() function in MainCtrl.js is triggered, which then calls the flowService as shown below: ...

Please provide the array of data in a single input field

Is there a straightforward method for entering an array of data into a single input field? For instance, let's say we have an input field named 'vacancies': "vacancies": [ 15,18,16 ] Something akin to this: https://i.sstatic.net/XFE ...

JavaScript array containing objects remains static

I'm facing an issue with a complex array of objects (I will only display the necessary nodes to explain the problem): var arr = [ { json: { doc: { id: 1, atualizacao:{ ...

Establishing global date restrictions for the DatePicker component in Angular 8 using TypeScript across the entire application

I am currently learning Angular 8 and I am looking to globally set the minimum and maximum dates for a datepicker in my application. I would like to accomplish this by using format-datepicker.ts. Any suggestions on how I can achieve this? Min date: Jan 1, ...

Convert a two-column layout on the web into a single-column layout for mobile devices, featuring dynamic

Is there a way to style this diagram with CSS that will work on IE11 and all major browsers? It seems like Flexbox doesn't support dynamic height. Do I need separate left and right columns for larger viewports and no columns for smaller viewports? ...

Updating Reference Models in Mongoose: A Simple Guide to Updating a Single Model

I have a scenario involving two models: Skill and Course. The challenge I face is ensuring that whenever I update the name of an existing skill, it should also automatically update the corresponding skill name within the course object where this skill is u ...

Executing a Shortcode Using a Button in Visual Composer for Wordpress

It should be easy to do this. I've got a great plugin with a modal newsletter signup form that offers various launch options, including manual launching with the following codes. https://i.stack.imgur.com/IGbsp.png My theme utilizes Visual Composer. ...

Using TypeScript's union type to address compatibility issues

Below is a small example I've created to illustrate my problem: interface testType { id: number } let t: testType[] = [{ id: 1 }] t = t.map(item => ({ ...item, id: '123' })) Imagine that the testType interface is source ...

Triggering the onClick event in React to invoke another class components

I'm currently working on implementing a modal popup (stored in the PostView class) so that it appears when any post in the postcontainer class is clicked. As I am new to React, I would greatly appreciate any suggestions for enhancing the code. Post C ...

Styling only for Angular 2 Components

How can component scoped styles be used to style elements differently based on their location within the site while still maintaining style scoping? For example, when using a "heart like" item created in this course, how can padding be added specifically i ...

Why is useEffect being executed twice?

For some reason, when I try to run useEffect for the first time page load, it ends up running twice. I can't seem to figure out why this is happening. Can someone please provide assistance? I'm currently using React 18 and I need help understand ...

Customizing Bootstrap Vue to prevent tooltips from opening on hover

I am currently using a tooltip similar to the example shown on Toggle Tooltip: <template> <div class="text-center"> <div> <b-button id="tooltip-button-1" variant="primary">I have a tooltip</b-button> </div& ...

What would be the optimal type for the second argument of the `simulate` method?

When using the simulate function, I am familiar with code like this: simulate("change", { target: { value: '7' } }); However, if my onChange function requires an object as a parameter, what should I pass in the second argument? interface myObj ...

Spotlight barn doors in Three.js are an innovative feature that

I have been experimenting with three.js to build a scene featuring spotlights. Is there a way to achieve the barn door effect for the lights in three.js? I attempted using small cubes as barn doors to block the light, but it was not successful. I am look ...

Instructions for manipulating and displaying a source array from a child component using Vue

I have a parent component with an array that I display in the template. My goal is to click on a link that uses vue-router with a dynamic id attribute, and then open a new component displaying only the element of the array that corresponds to that id. Howe ...

"Creating a dynamic Vue array using computed property from the provided dataset

Let's consider a scenario where data is retrieved from a store: let itemsData=[ {id:1,data:[...]}, {id:2,data:[...]}, {id:3,data:[...]} ] The goal here is to create another array, itemsSelected, that looks like this: let itemsSelected=[ {id:1 ...