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

The Vue.JS application encountered an error while making an API request, resulting in an uncaught TypeError: Cannot read properties of undefined related to the 'quote'

<template> <article class="message is-warning"> <div class="message-header"> <span>Code Examples</span> </div> <div class="message-body"> ...

send array to the sort function

How can I sort a data array that is returned from a function, rather than using a predefined const like in the example below: const DEFAULT_COMPETITORS = [ 'Seamless/Grubhub', 'test']; DEFAULT_COMPETITORS.sort(function (a, b) { re ...

What is the best way to apply a CSS class to a div element without affecting its child elements using JavaScript?

Currently, I am using JavaScript to add and remove a CSS class through a click event. Within my div structure, I have multiple similar divs. While I can successfully add and remove the class from my main div, I am facing an issue where the class is also ap ...

Is Selenium suitable for testing single page JavaScript applications?

As a newcomer to UI testing, I'm wondering if Selenium is capable of handling UI testing for single-page JavaScript applications. These apps involve async AJAX/Web Socket requests and have already been tested on the service end points, but now I need ...

What is the best way to merge two similar arrays of objects into one array object?

Apologies in advance if this question has been asked previously, I'm struggling with how to phrase it. Essentially, the API I'm using is returning an array of similar objects: const response.survey = [ { 1: { id: 1, user: user_1, points: 5 ...

Troubleshoot issues within ExpressJS

I am encountering an issue with the debugger in Visual Studio Code. It crashes upon startup, but runs smoothly when using nodemon to start the server. My application is connected to a MySql Database. I have attempted to reinstall the module without succes ...

Turn off bodyparser when uploading files in Node.js

This query is quite similar to another one on Stack Overflow regarding how to disable Express BodyParser for file uploads in Node.js. The solution provided there was for Express3, but when tested with the updated Express 4, it didn't work as expected. ...

Freeze your browser with an Ajax request to a specific URL

There is a function in my view that transfers a value from a text box to a table on the page. This function updates the URL and calls another function called update_verified_phone(). The update_verified_phone() function uses a model called user_info_model( ...

Error: HTMLAnchorElement.linkAction is attempting to access an undefined property 'add', resulting in an uncaught TypeError

Displaying the following: Error: Cannot read property 'add' of undefined at HTMLAnchorElement.linkAction const navigationLinks = document.querySelectorAll('.nav__link') function handleLinkAction(){ // Activate link navLin ...

In React JS, the material-ui Accordion component's onchange function is failing to retrieve the current value

I am encountering an issue with the @material-ui Accordion where the onChange function is not capturing the current value. For example, when I click on the panel1 icon, it opens panel2 instead of taking the current value on icon click. I have provided the ...

The overall outcome determined by the score in JavaScript

Currently, I am working with a dataset where each person is matched with specific shopping items they have purchased. For instance, Joe bought Apples and Grapes. To gather this information, individuals need to indicate whether they have made a purchase. I ...

Transmitting the Flag between PHP and JavaScript

I need help with setting a flag in PHP and accessing it in JavaScript. Currently, I have the following code: PHP if ($totalResults > MAX_RESULT_ALL_PAGES) { $queryUrl = AMAZON_SEARCH_URL . $searchMonthUrlParam . ...

Utilize Meteor's ability to import async functions for seamless integration into method calls

Encountering an issue with this Meteor app where the error TypeError: vinXXX is not a function occurs when attempting to call an exported async function named "vinXXX" from within a method call in a sibling folder, which has been imported in the methods f ...

Can you retrieve a reference/pointer to a specific property of an object in JavaScript?

I am looking to generate an HTML <input> element, and then access its value property so I can update the value through that reference: var input = document.createElement('input'); var valueRef = &(input.value); *valueRef = "Hello world!" ...

Utilizing Ionic Storage to set default request headers through an HTTP interceptor in an Angular 5 and Ionic 3 application

I'm attempting to assign a token value to all request headers using the new angular 5 HTTP client. Take a look at my code snippet: import {Injectable} from '@angular/core'; import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from ...

Adding an element within an ngFor iteration loop

I'm currently working on a code snippet that displays items in a list format: <ul> <li *ngFor="#item of items">{{item}}</li> </ul> These items are fetched from an API through an HTTP call. Here's the code snippet for tha ...

When utilizing the dispatch function with UseReducer, an unexpected error is triggered: Anticipated 0 arguments were provided,

Having trouble finding a relevant answer, the only one I came across was related to Redux directly. So here's my question that might be obvious to some of you. In my code, everything appears to be correct but I'm facing an error that says: Expect ...

Utilizing jQuery's .clone() function to duplicate HTML forms with radio buttons will maintain the radio events specific to each cloned element

I'm currently developing front-end forms using Bootstrap, jQuery, HTML, and a Django backend. In one part of the form, users need to input "Software" information and then have the option to upload the software file or provide a URL link to their hoste ...

Move the option from one box to another in jQuery and retain its value

Hey guys, I need some assistance with a jQuery function. The first set of boxes works perfectly with the left and right buttons, but the second set is not functioning properly and doesn't display its price value. I want to fix it so that when I click ...

Ensure that the assistant stays beneath the cursor while moving it

I am currently working on creating a functionality similar to the 'Sortable Widget', but due to some constraints, I cannot use the premade widget. Instead, I am trying to replicate its features using draggable and droppable elements: $(".Element ...