Custom(ized) Objects!
Goals:
- Create objects using object literal notation
- Modify existing objects using dot-notation
Coding Snippets:
- Custom objects can be created using the
Object
constructor:mars = new Object()
- A simpler alternative is to use object literal notation (using curly braces) which also allows you to define properties when creating an object, as illustrated on the left.
- Add, modify, or reference an object's properties using dot notation. This works for custom as well as built-in objects, such as Turtles.
Math and Computer Concepts:
- Objects are made up of properties consisting of name/value pairs. The name is a variable name. The value can be data of any type: Number, Boolean, String, or even Object.
- Objects permit us to make a single unit out of data that belong together. We can exploit this feature to keep programs organized, as illustrated in this Solar System program, which uses separate objects to track information about each planet.
- Being able to lump multiple pieces of information together in a single unit is also useful for passing around information within a program, such as to and from functions.
Activities:
Save each of the following in a folder called Objects.
- In HTML as in many other graphics systems, the origin is located at the top left corner of the screen, with the positive x and y values going to the right and down, respectively. Pencil Code interprets numeric data as HTML coordinates when they are expressed as objects with property names
pageX
andpageY
. For example,jumpto {pageX:0, pageY:0}
moves the turtle to the top left corner of the screen. Draw the HTML coordinate system usingmoveto
andjumpto
functions with HTML-coordinate arguments, saving your work as LabeledHtmlAxes. ColorEaters: Use dot notation to add
color
andsize
properties to each of 4 or more Turtles. Make the turtles move about randomly on a multicolored background. When a turtletouches
its own color on the background canvas, it should "eat" it, leaving a white dot behind.- HairdosRedux: Update the Hairdos program from the Images! lesson so that each time it runs, one of several hairdos is randomly added to a picture of your choice. Use objects to capture the data for each hairdo, with properties for the image URL and all necessary information to correctly size and position that image on screen.