I try to send a name and a color to the constructor function below. The method this.whatAreYou() should to retrieve these strings when called.
I want to display this on the screen.
I have the following code:
function Gadget(name, color) {
this.name = name;
this.color = color;
this.whatAreYou = function() {
return 'I am a ' + this.name+ ' ' + this.color;
};
}
string = Gadget(grass, green);
alert(string);
however the alert is not functioning. How can I achieve my desired behaviour?
Your Gadget isn’t a string. It just holds a function returning a string.
As you seem to try to create an instance of the Gadget class, you need to use the
newoperator.If
grassandgreenaren’t predefined variables but strings, you need to put them between quotes.Try