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.