Creating Objects in JavaScript Part 1
Going from writing ActionScript 3 (AS3) and Flex applications to HTML5/JavaScript is like stepping into a time machine! JavaScript (JS), while a very powerful language, lacks many of the object oriented (OO) programming features that have become standards of most modern languages. Things like strongly typed variables, multiple inheritance and clearly defined scopes are not available in JS. All of these nuances can make going from AS3 to JS… unpleasant. Have no fear though, over the next few blog posts I plan to discover and explain how to overcome these obstacles and better understand HTML5. I’m learning this myself, so bear with me and feel free to leave comments if something isn’t clear or is inaccurate. Sharing is caring.
Alright, so here we go. Lets start out just discussing some of the primitive objects that are built into AS3 and what their JS counterpart is.
| ActionScript3 Data Types | JavaScript Equivalent |
1. Object 2. Number | int | unit 3. String 4. Boolean 5. Array 6. Dictionary 7. Array 8. Date 9. Function 10. Class 11. Prototype 12. Getter / Setter |
1. Object 2. Number 3. String 4. Boolean 5. Object 6. Object 7. Array (Object) 8. Date 9. Function 10. Function 11. Prototype 12. Function |
Notice how many of those primitives are simply of type Object? That’s because everything except for those few primitives such as String, Number, Boolean, Array, and Date are either Objects or Functions. What about Prototype? Well that’s a special case I will discuss in more detail in a later post. (Note that just because JS and AS3 both have a ‘Date’ or a ‘String’ object, does not mean that they will have the same properties and functions.)
So how do we create our own objects in in JavaScript? One of the simplest ways is to declare them inline with code. This will give you an object that can be used in the global space or within functions, but doesn’t offer anything in the realm of reusability. Here’s an example where we create a new object with its own properties and a single function:
var artist = {
hunger: ‘starving’,
hands: ‘covered in paint’,
drink: function (){
return ‘Drinking lots of whiskey’}
}
As you can see, the functions and the properties we’ve declare within the var artist are available. But what would happen if we later put artist.drink = function { return ‘Drinking lots of milk’ }? The function would return ‘Drinking lots of milk!’, and lets face it, artists want scotch whiskey! So lets figure out how to make our artist object both reusable, and attempt to privatize some of those variables and functions. Observe our new Artist:
{code type=javascript}
function Artist( name, medium ) {
var name = name;
var hunger = 1; //
this.medium = medium;
this.getName = function() {
return name;
}
this. makeArt = function() {
hunger–;
}
this.feed = function( amount ) {
hunger += amount;
}
this.getHunger = function() {
return hunger;
}
}
// SCENARIO A
var a = new Artist( ‘DC’, ‘Oil Paint’);
alert( ‘Name: ‘ + a.name ) // Name: undefined
alert( ‘Name: ‘ + a.getName() ) // Name: DC
a.name = ‘I broke it.’
alert( ‘Name: ‘ + a.name ) // Name: I broke it
alert( ‘Name: ‘ + a.getName() ) // Name: DC
// SCENARIO B
a.feed( 5 );
alert( a.hunger ); // undefined
alert( a.getHunger() ) // 6
// SCENARIO C
alert( a.medium ); // Oil Paint
a.medium = ‘Clay’;
alert( a.medium ); // clay
// SCENARIO D
a.getHunger = function(){ return ‘aw crap, a developer can still break me!’ };
alert( a.getHunger() ) // aw crap, a developer can still break me!
{/code}
So we have a constructor function for Arist, that takes two parameters, a name and a medium. The name we put int to a basic ‘var name’ statement, which means that it will be accessible to everything within the function, but not outside of it. The medium property we assign to a this.medium. This is an important property in JS. ’this’ properties are available essentially public properties. We also have a var hunger, which is essentially private. As you can see, its used in the public functions for paint, feed and getHunger.
Scenario A
We create our new Arist. Next we ask for its name directly, and we are notified that it is undefined. Thats because the name property is private within the Artist function. To get the name, we need to call its getter function, getName(). We wanted the name to be read-only once our Artist is initialized. However, as you can see in SCENARIO A, you can still assign a new name property to our Artist. This doesn’t overwrite our artists actual name property.
Scenario B
Artists are typically starving, and our current artist is no exception. Every time our artist makeArt, he gets more hungry! The feed function takes a parameter and adds it to hunger. We don’t want a user to be able to manipulate hunger without feed or makeArt. Requesting to see hunger directly results in undefined.
Scenario C
Since we don’t care if the artist changes his medium at any time, that property was defined with a this in the constructor, and is there for a public variables.
Scenario D
Finally, we show that no matter what you do, JavaScript is a hugely dynamic language, and you just can’t save a developer from himself. You may able to make the logic in a function private, create getter/setters and make read-only properties, but all of that can be written over by just assign a new property to the function itself.
Thats all for now! I’ll continue to blog and write as I dive deeper into the language.
No CommentsClassic Snake In HTML5
While I’ve been developing Rich Internet Applications for the past five years, it has been a long time since I’ve had to program true HTML5, CSS and JavaScript. The last time I wrote a legitimate HTML based webpage, the industry standard was laying out the content in tables. Attempting to dive in and learn all the new pieces seemed daunting. I decided to start my focus on the Canvas component in HTML5 because of its relative closeness to the Canvas component in Flex.
My goal was to develop something that was animated, took advantage of keyboard and mouse clicks, and could be used on mobile devices. I created the classic game Snake. Use your WSDA keys to control the movement. Alternatively, for mobile devices without key support you can click in the top, bottom, right and left purple squares to move the snake in that direction.
[iframe: src="http://www.dcholth.com/html5/20101103/snake/snake.html" frameborder="0" width="410" height="410" scrolling="no"]
Drawing on the Canvas requires you to call the stroke() function. I feel silly even mentioning this, but it took me at least twenty frustrated minutes thinking my code wasn’t executing at all until I figured this out. If you do not call this function after creating your paths, nothing shows up on screen…
{code type=javascript}
gDrawingContext.beginPath();
gDrawingContext.strokeStyle = “#FF00FF”;
gDrawingContext.moveTo( 0, yB+ yB);
gDrawingContext.lineTo( gWidth, yB+ yB);
gDrawingContext.stroke(); /* CALL ME */
{/code}
Redrawing on the canvas is slow. At least it is on the iPad and my Droid Incredible. I had done a previous experiment where I had red squares bouncing all over the screen. This effect was made by redrawing both the grid and the red pixels each interval. While it looked smooth on my computer screen, it was extremely choppy on the mobile devices. To make the Snake game smooth, I’m only redrawing what is necessary. For the Snake, I’m drawing black squares over the tail, and adding red squares to the head to create the movement effect. I know that there must be ways to have smooth animations on mobile devices (I’ve seen them!) but they currently elude me. More research on this to come.
Clicking a Canvas within the mobile device browsers has a significant delay. While it does register the clicks, there is a delay between clicking, and having the snake change directions. I believe this is an issue with the touch screens trying to determine the intentions of the users finger on the screen within a browser. I’d like to do further tests to find out if this is something that I can fix, or at least predict exact delays. I noticed on the Droid Incredible, clicking the Snake game causes the entire Canvas to highlight green, as if its reacting to it like one big button.
There does not seem to be a ‘focus’ in HTML5 Canvas. I had originally programmed the game to use the arrow keys to control the direction of the snake. I had to change this because there doesn’t appear to be a way to differentiate that the arrows are supposed to control the Snake game (IE: The snake game has focus) and not the scrollbars of the webpage. So clicking down would send the snake in a downward direction, but it would also scroll your page down. This is a little difficult to see on my blog, because I am embedding the Snake game in an iFrame to make it work with WordPress.
Thats all for now! Feel free to browse the project code. The major code components to this application are:
- http://www.dcholth.com/html5/20101103/snake/snake.html
- http://www.dcholth.com/html5/20101103/snake/snake_code.js



