What is the best way to transfer data from a custom method and use it in another method within my constructor function in Javascript?

As I pondered a suitable example, I devised a constructor function centered around precious metals. This function accepts the type of metal and its weight as parameters. Within this constructor, there are two methods: one to verify if the precious metal (gold or silver) is authentic and another to calculate its value based on the spot price (although, please note that the spot price used here is merely for illustration purposes).

Imagine a scenario where a customer presents a silver piece containing 80% silver content. In such a case, I intend to incorporate this silver purity percentage into my metalValue method. How can I achieve this?

Below is the code snippet, with a JSFiddle link provided for your convenience at http://jsfiddle.net/bwj3fv12/. This example serves as an aid in enhancing my comprehension of constructors.

HTML:

<div id="testDiv">test Div</div>
<div id="testDiv2">test Div2</div> <br /><br />

JavaScript:

var PreciousMetals = function(metal, weight){
    this.metal = metal;
    this.weight = weight;  //weight in ounces

    this.authentic = function(colorTest){
        var metalPurity;
        var zero = "";
        if (this.metal == "silver"){
            switch(colorTest){
                case "brightred":
                    metalPurity = 1;
                    break;
                case "darkred":
                    metalPurity = 0.925;
                    break;
                case "brown":
                    metalPurity = 0.80;
                    break;
                case "green":
                    metalPurity = 0.50;
                    break;
                default:
                    metalPurity = 0;
            }
        } else if(this.metal == "gold"){
            switch(colorTest){
               case "green":
                   metalPurity = "base metal or gold plated";
                   break;
               case "milk colored":
                   metalPurity = "gold plated sterling silver";
                   break;
               case "no color":
                   metalPurity = "real gold";
                   break;
               default:
                   metalPurity = "Could be a fake, try different test";
            }
        }
        return metalPurity;
    }

    this.metalValue = function(){
        var sum = 0;
        var spotPrice;
        if (this.metal == "gold"){
           spotPrice = 1000;
        } else if(this.metal == "silver"){
           spotPrice = 15;
        }
        sum = spotPrice * this.weight;
        return sum;        
    }
}

var customerCindy = new PreciousMetals("silver", 2);

document.getElementById('testDiv').innerHTML = customerCindy.authentic("brown");

document.getElementById('testDiv2').innerHTML = customerCindy.metalValue();  //The desired result should be 30.

While it's possible to compute the total value by multiplying both methods directly, the objective here is to leverage the information from the authentic method to facilitate the calculation within the metalValue method.

Answer №1

To maintain the separation of logic in your constructor function for these two methods, you may consider adding a third method that handles the task of multiplying the results.

var PreciousMetals = function(metal, weight){
    this.metal = metal;
    this.weight = weight;  //weight measured in ounces

    this.determineAuthenticity = function(colorTest){
        var metalPurity;
        var zero = "";
        if (this.metal == "silver"){
            switch(colorTest){
                case "brightred":
                    metalPurity = 1;
                    break;
                case "darkred":
                    metalPurity = 0.925;
                    break;
                case "brown":
                    metalPurity = 0.80;
                    break;
                case "green":
                    metalPurity = 0.50;
                    break;
                default:
                    metalPurity = 0;
            }


        }else if(this.metal == "gold"){
           switch(colorTest){
                case "green":
                    metalPurity = "base metal or gold plated";
                    break;
                case "milk colored":
                    metalPurity = "gold plated sterling silver";
                    break;
                case "no color":
                    metalPurity = "real gold";
                    break;
                default:
                    metalPurity = "Could be a fake, try different test";
            }
        }
        return metalPurity;
    }

    this.calculateMetalValue = function(){
        var sum = 0;
        var spotPrice;
        if (this.metal == "gold"){
           spotPrice = 1000;
        }else if(this.metal == "silver"){
           spotPrice = 15;
        }
        sum = spotPrice * this.weight;
        return sum;        
    }

    this.calculateNetValue = function(colorTest){
        return this.determineAuthenticity(colorTest) * this.calculateMetalValue();    
    }
}

Check out the operational JSFiddle here - https://jsfiddle.net/bwj3fv12/

Answer №2

If you were looking to incorporate the results of a purity check into the metalValue variable, you could easily update it like so:

this.metalValue = function(colorTest){
    // ...
    sum = spotPrice * this.weight * this.authentic(colorTest);
    return sum;        
}

You can then execute it by calling:

customerCindy.metalValue('brown');

In a more realistic scenario, purity would likely be treated as a permanent property rather than a temporary value for a method like this. Nevertheless, for the sake of this example, it serves its purpose without any issue.

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 for generating Json using information from a form?

Recently, I embarked on a project that involves creating online tours via a form filled out by the administrator. The data submitted through the form is then mapped into a Mongoose Schema and transformed into JSON. In the createcontent.js file, I utilized ...

Adjusting mesh rotation on elliptical curve using mousewheel scrolling

I have arranged several plane meshes in a uniform manner along an elliptical curve. During the animation loop, I am moving them along the ellipse curve using curve.getPointAt with time delta and applying the matrix. Additionally, I am attempting to incor ...

Connection error: API is down

The current issue I am facing with the application I'm developing is that it is not responding with the API address for weather data. Despite getting a response from Ajax, the specific weather API I am trying to call remains unresponsive. I have exha ...

activate a single on.click event to trigger additional actions - utilizing javascript and jQuery

My website features dynamically generated buttons that lead to specific pages. The challenge I'm facing is retrieving the automatically generated data-num value for each button and using it as a jQuery selector to redirect users to the corresponding p ...

Assign a variable name to the ng-model using JavaScript

Is there a way to dynamically set the ng-model name using JavaScript? HTML <div ng-repeat="model in models"> <input ng-model="?"> </div JS $scope.models= [ {name: "modelOne"}, {name: "modelTwo"}, {name: "modelThree"} ]; Any ...

The difference between calling a function in the window.onload and in the body of a

In this HTML code snippet, I am trying to display the Colorado state flag using a canvas. However, I noticed that in order for the flag to be drawn correctly, I had to move certain lines of code from the window.onload() function to the drawLogo() function. ...

The significance of package-lock.json: Understanding demands vs dependencies

Within the dependency object of package-lock.json, there exist both requires and dependencies fields. For example: "requires": { "@angular-devkit/core": "0.8.5", "rxjs": "6.2.2", "tree-kill": "1.2.0", "webpack-sources": "1.3.0" }, "d ...

The output stored in the variable is not appearing as expected

https://i.sstatic.net/VWCnC.pnghttps://i.sstatic.net/UoerX.pnghttps://i.sstatic.net/n52Oy.png When retrieving an API response and saving it in the "clima" variable, it appears as undefined. However, when using console log, the response.data is visible ...

How can you hide all siblings following a button-wrapper and then bring them back into view by clicking on that same button?

On my webpage, I have implemented two buttons - "read more" and "read less", using a Page Builder in WordPress. The goal is to hide all elements on the page after the "Read More" button upon loading. When the button is clicked, the "Read More" button shoul ...

The error message "Unable to retrieve property 'commands' of undefined (discord.js)" indicates that the specified property is not defined

As I try to incorporate / commands into my Discord bot, I encounter a persistent error: An issue arises: Cannot read property 'commands' of undefined Below is my main.js file and the problematic segment causing the error: Troublesome Segment c ...

What is the best way to display a single div at a time?

I have a setup with three sections, each containing two divs. The first div has a button that, when clicked, should open the next div while closing any other open div. However, I am facing an issue where clicking the button again does not close the corresp ...

Get the characters from a URL following a specific character until another specific character

Having some difficulty using JavaScript regex to extract a specific part of a URL while excluding characters that come after it. Here is my current progress: URL: With the code snippet url.match(/\/[^\/]+$/)[0], I am able to successfully extrac ...

Unraveling the Mystery of jQuery AJAX Response: Where Have I Gone Astray?

$.ajax({ type: 'POST', url: 'place/add', data: { lat: 45.6789, lng: -123.4567, name: "New Place", address: "123 Main St", phone: "555-1234", review: "Great place!", cat ...

Which Express.js template allows direct usage of raw HTML code?

I am in search of a template that utilizes pure HTML without any alterations to the language, similar to Jade but keeping the HTML as is. The reason behind this inquiry is: I prefer the simplicity and clarity of HTML I would like to be able to easily vi ...

Establish a timeout for the Material UI drawer to close automatically after being opened

I am looking for a way to automatically close the drawer after a specific duration, but it seems that material UI drawer does not have the necessary props for this. Is there a workaround using transitionDuration or perhaps adding a setTimeout in my functio ...

The toggling feature seems to be malfunctioning as the div section fails to display

I'm facing an issue with my Django project while working on a template. I want to toggle the visibility of a div element between hiding and showing, but the function I used isn't working for some reason. I borrowed the function from a different t ...

What are the differences between ajax loaded content and traditional content loading?

Can you explain the distinction between the DOM loaded by AJAX and the existing DOM of a webpage? Is it possible to load all parts of an HTML page via AJAX without any discrepancies compared to the existing content, including meta tags, scripts, styles, e ...

Combining Strings and Integers in Javascript

Currently, I am facing a frustrating syntax issue with my code. I am using Scissors, a Node Module for managing pdf files. The documentation describes the syntax for selecting specific pages of the Pdf: var scissors = require('scissors'); var p ...

"How to retrieve the height of an element within a flexslider component

I need some assistance with using JavaScript to determine the height of an element within a flexslider. There are two challenges I am facing. When I attempt to use a regular function getHeight(){ var h = document.getElementById("id-height").style.height; ...

Utilizing JQuery and Jade to extract and display information from a Node.js server

I am currently working with the Jade framework for frontend and using Node.js & express for backend development. When rendering a view with data, I am encountering an issue where I can't access this data using JQuery. Below is my service in Node.js ...