Programming with a combination of Javascript, Angular, and Prototype to efficiently manage and

I am in a bit of a quandary, as I wish to create a function that will clear all the properties of an object and make it available to all instances of that object. To achieve this, I have added a prototype function called clear(). Here is the code snippet:

(function () {

Supplier.$inject = [];

angular.module('webclient').factory('Supplier', Supplier);

function Supplier() {

    Supplier.prototype = {
        clear: function () {
            for (var key in this) {
                //skip loop if the property is from prototype
                if (this.hasOwnProperty(key))
                    continue;


                console.log("key:" + key);
                this[key] = undefined;
            }
        },
    }

    return Supplier;
};
})();

Therefore, my goal is to be able to clear all properties of the current supplier object. For instance, if the supplier object had the following properties:

SupplierID:21, Email:None

I would like to reset these properties to undefined. This can be achieved using the following steps:

var supplier = new Supplier();

supplier.SupplierID = 21; supplier.Email = "None";

To set each property to undefined, I would use the following code:

supplier.clear();

Any suggestions or ideas on how to improve this implementation?

Thank you!

Answer №1

Give this a shot: (Plunker)

function Manufacturer() {
    var manufacturer = function() {};
    manufacturer.prototype.clear = function() {
      for (var key in this) {
          if (!this.hasOwnProperty(key))
              continue;
          delete this[key];
      }
    };
    return manufacturer;
}

Answer №2

The hasOwnProperty method will return true only if the key is not in the prototype chain. It's important to note that the prototype should be assigned outside of the constructor function. Here is an example of how your code should be structured:

function Supplier() { }

Supplier.prototype = {
    clear: function () {
        for (var key in this) {
            if (this.hasOwnProperty(key)) {
                console.log("key:" + key);
                this[key] = undefined;
            }
        }
    },
}

Answer №3

Avoid assigning properties as undefined, instead use delete():

delete this[key];

@jcubic makes a valid point, hasOwnProperty will return true even if the key is not in the prototype...

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

Special character Unicode regex for names

After spending the entire day reading about regex, I am still struggling to fully grasp it. My goal is to validate a name, but the regex functions I have found online only include [a-zA-Z], omitting characters that I need to allow. Essentially, I require ...

Change object values to capital letters

Upon retrieving myObject with JSON.stringify, I am now looking to convert all the values (excluding keys) to uppercase. In TypeScript, what would be the best way to accomplish this? myObj = { "name":"John", "age":30, "cars": [ { "name":"Ford", ...

Initial React render fails to retrieve API data

I've encountered an issue during development where the page loads before the API data is sent. I attempted to use asynchronous functions, but it didn't resolve the problem as expected. I suspect that my approach may be incorrect. Here's a sn ...

Retrieve the order in which the class names are displayed within the user interface

In the following code snippet, each div element is assigned a common class name. <div id="category_9" class="list_item" data-item_ids="[38]"</div> <div id="category_2" class="list_item" data-ite ...

Setting up paths to bypass authentication on an Express website

Currently, I am in the process of developing an application using node and express. I have implemented a passport authorization middleware for all routes as part of my highly modular approach to building the app. One challenge I have encountered is when tr ...

AngularJS table with resizable columns for seamless data browsing

Most examples of expandable tables using ng-repeat feature a separate content for the expanded row, like an independent table inside the detail row. I have implemented many expandable tables using these methods, similar to the following: <tr ng-repeat ...

Convenient ways to connect data between a database and Firebase authentication system

After beginning a basic app using Firebase 3 and Angular 1, I implemented an authentication system through Firebase for user registration and login. Currently, I am storing message data in the Firebase database. My main question is: how can I connect user ...

Eliminate lower values in select 1 if the value selected in select 2 is higher

I am struggling with a particular piece of code and could really use some assistance. Within my project, I have two select boxes. The first box allows users to select the "from" year, while the second box is for selecting the "to" year. What I'm tryi ...

Retrieve information from a JSON file but specifically for a single entry

Here is a JSON object I have: { "success": true, "return": { "totalItem": 7, "totalPages": 1, "pageSize": 7, "items": { "phones": [ "(48) 9999-9999" ], "users": { "manager": { "id_user": "581 ...

The jQuery .animate function seems to be malfunctioning

I recently came across this jsfiddle link: http://jsfiddle.net/2mRMr/3/ However, the code provided is not functioning as expected: setInterval(function () { box.animate({ left: function (i, v) { return newv(v, 37, 39); }, ...

Tracking the number of form submissions on a PHP website

I am looking to add a counter feature to my website where every time a form is submitted, the count increases for all visitors. The starting number will be 0 and each form submission will increment the count. While I can manage the count using JS/jQuery w ...

The fixed navigation bar shows a flickering effect while scrolling at a slow pace

Currently facing a challenge with our sticky navigation. Noticing a flickering issue on the second navigation (sticky nav) when users scroll down slowly. The problem seems to be specific to Chrome and Edge, as it doesn't occur on Firefox, IE11, and S ...

Retrieving FormData() parameters sent via Ajax with PHP

After successfully testing FormData() with jQuery.ajax, I encountered a roadblock when trying to implement a progress bar for file uploads using the same method. This led me to use AJAX directly and post form data, but unfortunately, retrieving the form da ...

Utilizing Radio buttons for validation in react-hook-form

After creating a form with radio buttons and implementing validation using React Hook Form, I encountered an issue where the console always displayed "on" regardless of the selected radio button. <div className=""> <label ...

Changing the colors of multiple buttons in a React Redux form: a step-by-step guide

When using Redux Form Wizard on the second page, I have two buttons that ask for the user's gender - Male or Female. The goal is to make it so that when a user clicks on either button, only that specific button will turn orange from black text. You ...

Display additional images with "Show More" view

I'm looking to create a view similar to the one shown in this image: https://i.stack.imgur.com/AZf61.png Within my FlatList, all the data is being populated including these thumbnails. These thumbnails are stored in an array of objects where I retri ...

Incorporate an icon into an Angular Material input field

I want to enhance my input search bar by adding a search icon from Angular Material : <aside class="main-sidebar"> <section class="sidebar control-sidebar-dark" id="leftMenu"> <div> <md-tabs md-center-tabs id=" ...

Struggling to retrieve the most recent emitted value from another component in Angular?

Hello everyone, I am currently attempting to retrieve the most recent updated value of a variable from the component app-confirm-bottom-sheet in the app-bene-verification.ts component, but unfortunately, I am unable to achieve this. Below is the code snipp ...

Having trouble with setting up the next image configuration for graphcms' images

I've been using graphcms solely for my image assets and trying to integrate them into my Next JS (v12.0.1) frontend. However, I keep getting the error message hostname not configured in next.config.js, even though I have already specified it in my nex ...

The 'classProperties' React component module is currently not enabled

Encountering an error while running my react module 'classProperties' isn't currently enabled (44:11): } 43 | // componentDidUpdate or try this > 44 | onClick = (e) => { | ^ 45 | e.preventDefault(); 4 ...