PDA

View Full Version : Constructor Functions



rissa146
01-20-2016, 12:36 AM
I don't understand my professor and what is wrong with my problem. Can you help me?

correctionfunction Shape(height, width) {
//creates an instance field not a static field
this.height = height;
this.width = width;
return height * width;}Shape.prototype.calculateArea = function Shape(height, width){
console.log( Shape);

}

Shape(5,5)
Teacher: There is still a small syntax issue with the calculateArea function.
Me"
i get no errors
Teacher: When you add to the prototype of Shape you don't have to call it by its name again. You can attach any generic function to it as the calculateArea function.


It's won't throw an error in the console bc it is correct but it's not the way we add properties to the prototype.

The area should be returned when you call calculateArea on a new shape instance.


For example...


var rectangle = new Shape(2,3)
rectangle.calculateArea() should return 6


When you add the function that will calculate the area to Shape.prototype.calculateArea you will get this behavior.

Remember from class that a constructor function is a special function that creates objects for us when we invoke it using the new keyword.

If we want to add functionality to the object created by the constructor we can add a method to the constructor's prototype property.


For example.

To add a function that will log the height we can do the following...


Shape.prototype.logHeight = function() { console.log(this.height) };

So when I create a new shape object and call logHeight on it it will log its height like in the following example...

var square = new Shape(2, 2);
Square.logHeight(); will log 2 to the console


In the method definition for logHeight the "this" keyword refers to the object that logHeight() is being called on.

Does that make sense?
Me: Shape.prototype.calculateArea = function Shape(height, width){
console.log(height * witdth);
Teacher:
Take a look at this example:


Shape.prototype.logHeight = function() { console.log(this.height) };

There a few things that are different here than what's in your example.

If you can rewrite what you have to match the syntax of what I have then you'll have it.

Give it a shot and let me know if anything is not clear. I'm here to try to make it make sense. :)
Me:ok

Beverleyh
01-20-2016, 06:27 AM
I'm not sure why you're asking here when you have an instructor/teacher who is helping you, AND asking you to return to them if you don't understand. This feels like a follow-up to a homework assignment, and unfortunately we do not do homework for people. If you are having problems you should return to your teacher in the first instance and discuss it with them - it is more conducive to your development/learning if your teacher has a better understanding of your problem areas as they will be able to give dedicated assistance in relation to your project and needs.