I was asked to create a function that writes the property of a “type” that is send through a function to a cookie. I have never used javascript enough to understand it and this particular request is really particular I have been looking for an explaination of similar code for over 8 hours.
If I have the follow variable declared:
var types = {
"sugar" : { "color" : "blue", "weight" : 1200, "decoration" : "frosting"},
"chocolate chip" : { "color" : "brown", "weight" : 12, "chocolateType" : "milk"}
};
And the following function which returns the weight of the product.
CookieBase.prototype.getWeight = function() { return this.weight; };
How would I write to a cookie the properties of any type sent to the function, given it was actually declared. Would I be correct that the this in the getweight function is the types variable?
Here is the entire code fragment:
function CookieBase() {}
CookieBase.prototype.getWeight = function() { return this.weight; };
var CookieFactory = function(){
var types = {
"sugar" : { "color" : "blue", "weight" : 1200, "decoration" : "frosting"},
"chocolate chip" : { "color" : "brown", "weight" : 12, "chocolateType" : "milk"}
};
return {};
}();
I am not looking for the code itself I would really like somebody to explain the concept to me. This is for a screening process for a job, so I want to give them my own code, but I am not familar with this concept.
Here is the question and what they want exactly:
In CookieFactory implement a public method named bakeCookie that takes a single parameter — type. This method should create a cookie base instance with properties of the requested cookie type appended to it. If the type cannot be created return null. This code should not be more than about 10 lines long.
To set an arbitrary property on an object, you can use the bracket syntax:
You can also loop over the property names of an object using
for:Combine those and you can copy the properties of one object to another. This gets you most of the way to implementing mixins, which sounds like what they’re asking for.