ObjectExercises

From GIS CS4
Jump to: navigation, search

Ex 1. Define Object: Rectangle Area

First

  • Watch: Object Types

https://www.khanacademy.org/cs/programming/object-oriented/p/object-types

  • Do Challenge: Double Rainbow

https://www.khanacademy.org/cs/programming/object-oriented/p/challenge-double-rainbow

Below is an outline of an object representing a rectangular area on the canvas:

var RectArea = function(zval1, ...)
{
    // add properties here ...
    this.prop1 = zval1;
};
  • What other properties would you expect this object to have,(e.g. position/dimensions/colour)?
  • Add these properties into your object.
  • Write a function that displays your rectangle on the canvas using the properties.
var drawRect = function(zRect) 
{
    // your code goes here...
};
  • Declare two instances of your RectArea object with different properties (colour/position,etc).
var myRect1 = new RectArea(valx , , ...);
var myRect2 = new RectArea(valx , , ...);
  • call the drawRect function on each instance to display them.
drawRect(myRect1);
drawRect(myRect2);
  • SAVE YOUR CODE!

Ex 2. Object Methods

First

  • Object Methods:

https://www.khanacademy.org/cs/programming/object-oriented/p/object-methods

  • Do Challenge: Smiley Face

https://www.khanacademy.org/cs/programming/object-oriented/p/challenge-smileyface

  • Convert your draw function into a method.
// the draw method
RectArea.prototype.draw = function() 
{
    // ...    
};
  • Write code to invoke the method to draw your rect object.
myRect1.draw();
...
  • SAVE YOUR CODE!

Ex 3. Object Inheritance

First

  • Object Inheritance:

https://www.khanacademy.org/cs/programming/object-oriented/p/object-inheritance

  • Challenge: Flower Grower

https://www.khanacademy.org/cs/programming/object-oriented/p/challenge-flower-grower

  • Define a new object (TextArea) to display text on a rectangular background (base TextArea on RectArea).
var TextArea = function(zPropVal1, ... , zPropValx)
{
    // initialise rect properties
    RectArea.call(this, //rect properties//);

    // initialise text properties
    this.textProp1= zPropVal1;
    ...
};

TextArea.prototype = Object.create(RectArea.prototype);
  • What other properties would you expect this object to have,(e.g. text string/size/colour)?
  • Add these properties into your object.
  • Write a method to display the rectangle with the text.
TextArea.prototype.display = function(zStr) 
{
    this.displayRect(); // display the rect background

    // display the text
    // Your code goes here ...
};
  • Declare instances of your object.
var myTextArea = new TextArea(val , , ...);
  • Call the method to display these instances.
myTextArea.display(str);
  • SAVE YOUR CODE!


  • Object Oriented Code Review

Code Review

Personal tools
Namespaces

Variants
Actions
Navigation
Tools