Skemelio Skemelio - 5 months ago 12
Javascript Question

Javascript: How to store an object in a reference

I am new to Javascript and I am getting highly confused.

I created an object,

var recipe = {name:"", price:10, details:"", img_path:""};


and I created a function that it's something like a constructor. It gives values to the object's properties,

function recipeInstantiation( name, price, details, img_path){
recipe.name = name;
recipe.price = price;
recipe.details=details;
recipe.img_path = img_path;
// I dont know what to return here
//maybe return recipe;
}


And then I need to pass recipe object to a reference,

var recipe2 = recipe;

Is that correct?

KMC KMC
Answer

objects are reference types and your class definition should follow javascript language constructs and conventions (i.e use pascal case for classes)

go here and learn http://www.w3schools.com/js/js_objects.asp

----------------------------------

    //class definition that describes a recipe
    function Recipe( name, price, details, img_path){
    //javascript use this keyword to define data fields.
            this.name = name;
            this.price = price;
            this.details=details;
            this.img_path = img_path;

    }


    function displayRecipe(recipe){
         //display recipe as html
    }


----------------------------------
    var newReceipe = new Recipe("Pasta", 1000, "Something", "img/pasta.jpg");
    displayRecipe(newReceipe )
Comments