Issue With Prototype In JS
For my class I needed to create a constructor, object, and prototype. Unfortunately I cannot get the prototype to work and was wondering if someone could help me understand how to
Solution 1:
var pizza = Pizza(); //undefined
var pizza = new Pizza() //your obj
i am new, but try this.
Solution 2:
First of all, you're instantiating your object incorrectly. You must prefix new object instances with the self explanatory new operator.
Secondly, you reference instance values with this. In an prototype function, you can access instance variables by prefixing the variable with this. Doing this.size = size in the constructor will yield the value you passed to the constructor anytime you call this.size. Therefore your functions should reference those values like so instead of the variable which you're setting the input val from.
Here's how your code should look:
function Pizza(size, sauce, cheese, meat1, meat2, veggie1, veggie2) {
this.size = size;
this.sauce = sauce;
this.cheese = cheese;
this.meat1 = meat1;
this.meat2 = meat2;
this.veggie1 = veggie1;
this.veggie2 = veggie2;
}
Pizza.prototype.price = function() {
return this.size +
this.sauce +
this.cheese +
this.meat1 +
this.meat2 +
this.veggie1 +
this.veggie2 + 0;
}
var pizza = new Pizza(1, 1, 2, 1, 2, 3, 1);
console.log(pizza) // Pizza instance
console.log(pizza.price()) // returns computed instance values
console.log(pizza.sauce) // access instance value
In your case, you would use the above example like so:
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
$("form").fadeOut();
var inputtedSize = parseInt($("#size").val());
var inputtedSauce = parseInt($("#sauce").val());
var inputtedCheese = parseInt($("#cheese").val());
var inputtedMeatOne = parseInt($("#meat1").val());
var inputtedMeattwo = parseInt($("#meat2").val());
var inputtedVeggieOne = parseInt($("#veggie1").val());
var inputtedVeggieTwo = parseInt($("#veggie2").val());
var sizeChoice = $("#size option:selected").text();
var sauceChoice = $("#sauce option:selected").text();
var cheeseChoice = $("#cheese option:selected").text();
var meatChoiceOne = $("#meat1 option:selected").text();
var meatChoiceTwo = $("#meat2 option:selected").text();
var veggieChoiceOne = $("#veggie1 option:selected").text();
var veggieChoiceTwo = $("#veggie2 option:selected").text();
var pizza = new Pizza(inputtedSize, inputtedSauce, inputtedCheese, inputtedMeatOne, inputtedMeattwo, inputtedVeggieOne, inputtedVeggieTwo);
$("#total").fadeIn();
$(".total").text(" " + "$" + pizza.price());
$(".size").text(" " + pizza.size);
$(".sauce").text(" " + pizza.sauce);
$(".cheese").text(" " + pizza.cheese);
$(".meat1").text(" " + pizza.meat1);
$(".meat2").text(" " + pizza.meat2);
$(".veggie1").text(" " + pizza.veggie1);
$(".veggie2").text(" " + pizza.veggie1);
});
});
Post a Comment for "Issue With Prototype In JS"