I am working my way through understanding how to create a constructor with properties and methods. The one below I have written and tested but it does not work. Could someone take the time to help me understand what it is that would make this not work. Understand that I have searched Google, I am reading books, etc., but needs some hands on support in understanding the concept with creating my own. Thank you.
function ball( type, grip, shape ) {
this.type = type;
this.grip = grip;
this.shape = shape;
this.caught = function( who,how ) {
this.who = who;
this.how = how;
};
this.player = function() {
return (who + "caught the ball" + how + "that was a" + type + "shaped like
a " + shape + "thrown with a" + grip);
};
};
var baseball = new ball("Mickey Mantle","sliding","baseball","circle","fastball");
console.log(ball);
Edit:
From the answers below – thank you for sharing – I have created my jsfiddle and can’t comprehend why the caught property is not working. How am I supposed to set the attributes for this method??
In your player function, you need to reference the variables who, how, type, shape and grip using this, i.e.
Furthermore, functions common to all objects of type ball should be put into the prototype, so that the function only will be created once:
It is also common convention to start the constructor function name with an uppercase letter, like B in your case (so your constructor function’s name is Ball, not ball).
Updated answer
You forgot to call the
caughtfunction on the baseball object, like so: