Quantcast
Channel: Stroep » html5
Viewing all articles
Browse latest Browse all 2

Javascript for AS3 developers

$
0
0

This article is some training for your JavaScript skills. I love Actionscript , and I am also starting to like JavaScript. However, coding in JavaScript (if you’re an flasher) feels like Actionscript 1.0. It’s a pity there aren’t decent editors, especially if you want to write object-oriented-code, which is kinda possible with JavaScript . At the moment I think VisualStudio has a great (best?) JavaScript editor, but I really wish there was a tool for JavaScript like FlashDevelop (a clean editor for Actionscript projects) with great intellisense, code completion and snippets etc. But we should not focus on tools, lets focus on the language and get the most out of it. HTML5 is an hot topic today, and it seems using JavaScript is an important part of it, so why not learn more of it? I have seen some stunning HTML5 examples over the last year. As a developer it is very interesting to see how others code JavaScript. By the way; Personally I find it very funny to see how JavaScript has changed it’s ‘image’. Some of us remember the good days in Netscape. JavaScript was .. *kuch* not fast and associated with ugly rainbow mouse pointers and aggressive popup screens. Now it is mostly associated with HTML5, which has a more friendly association 😉
I think the ‘image’ of JS has slowly changed after great frameworks like jQuery have reached the developers. I think jQuery is awesome, I advice to give jQuery a try.

Anyway, there are (ofcourse) some techniques to code like Actionscript in JavaScript. These snippets have helped me to understand object oriented JavaScript. For too long I did not even tried to learn what was possible with JavaScript because I thought it was a very limited language. Maybe some information is outdated; I am still learning, so please share your feedback.

Object oriented javascript

In javascript it is possible to create sort-of classes, public and private vars, getters/setters and there are even constructors. A function could be seen as a class. This is a bit strange at first, but if you use it for a while you will understand. Now lets create our own class right now. Note: Javascript is prototype based language and natively hasn’t real classes, so all we do is work around this, and find some structure in the architecture of our applications/games.

Lets port some stuff of this Color Class to javascript. It has private vars and public functions.

Declare classes

Defining classes is as easy as defining functions, because you could consider as almost the same. After creating an function, you could already make some instances of it. The example below creates a Color class with a public variable called value. After that we create 2 instances of the Color class with some other values.

Note: I use the same code conventions as Actionscript: Classes should be UpperCased, functions/vars should be lowerCased and constants should be FULL_CAPS. I use an underscores for private vars.

function Color( value )
{
    this.value = value || 0;
    alert("Color created with value: " + value)
}

var myRedColor = new Color(0xFF0000); // create instance of Color  (a red one)
var myOrangeColor = new Color(0xFFCC00); // create instance of Color  (an orange one)
alert( myRedColor.value );
alert( myOrangeColor.value );
 

Public / Private

In actionscript it is very useful to use encapsulation, which is a mechanism for restricting access to other objects. The previous+following example should work in all browsers. The difference between public and private vars/functions in javascript can be declared like this:

function Color( value )
{
    // public variable
    this.value = value || 0xFFFFFF; // set default value to 0xFFFFFF for parameter if it isn’t defined

    // private variable
    var _name = "test";

   // public function
   this.getRandomColor = function( )
  {
     return Math.random() * 0xFFFFFF;
  }

  // private function
  function getNiceColor()
  {
     return 0xffcc00;
  }
}

// create instance of Color
var color = new Color(0xFF0000);
alert( color.value ); // returns red color
alert( color.getRandomColor() ); // returns random color

// not possible :
alert( color.getNiceColor() ); error in console; property does not exist, because function is private.
alert( color._name ); // error in console; property does not exist, because variable is private.
 

I think with this principles (maybe in combination with namespaces, see below) you can create clean javascript code.

Packages > Namespaces

Now before using classes in javascript I had some conflicts with function and variable names because there were unwanted duplicates. I have written a little helper tool to use namespaces. It helps to prevent those conflicts. Now it looks more like Actionscript 3, only there is no such thing like ‘imports’. This snippet works in all browsers.

/// create namespace like ‘com.yourcompany.projectname’
function Namespace(namespace)
{
    var parts = namespace.split(".");
    var root = window;
    for(var i = 0; i < parts.length; i++)
    {
        if(typeof root[parts[i]] == "undefined")
        {
            root[parts[i]] = {};
        }
        root = root[parts[i]];
    }
}

// creating my own namespace here
Namespace("nl.stroep.utils");
nl.stroep.utils.Color = function(value) // create class inside package
{
  this.value = value || 0xFFFFFF;
}

var myRedColor =  new nl.stroep.utils.Color(0xff0000);
alert(myRedColor.value);
 

Getters and Setters

Now it is possible to use getters and setters. NOTE (!): Ofcourse this method does not work in IE, so this is pointless but also a bit cool to see how far we could go. Anyway there are 2 ways to define them. Read more about it here. I think the __defineGetter__ way is better; it looks ugly but you still have access to private objects.

Take a look at this getter/setter declaration example. It’s not as clean as AS3 getters/setters but it works like a charm in my browser 😛

function Color( value )
{

   /* public getter */
   this.__defineGetter__("value", function()
   {
        alert("getter called; current value: " +value);
        return value;
    });
   
   /* public setter */
   this.__defineSetter__("value", function(val)
   {
        alert("setter called; new value: " +val);
        value = val;
    });
   
   // public variable. For a strange reason I have to put this below the get/set definition.
   this.value = value || 0xFFFFFF;
}

// create instance of Color
var color = new Color(0xFF0000);
color.value; // getter
color.value = 0xff0000; // setter
 

Constants

Javascript has a const too, you could use it instead of var. Ofcourse this is not implemented in IE, so it is also pretty pointless to use.

Mix them all

Now lets use namespaces, getters/setters and private/public variables and functions together.
This is a simplified ported version of this Color Class.
With this class you can modify the red,green and blue channels of a color individually. In the original class it is possible to lighten/darken the color too, but for this post I left these functions, because this only illustrates the possibilities of nice OO javascript.

Namespace("nl.stroep.utils");
nl.stroep.utils.Color = function( color )
{   
    /* PUBLIC FUNCTIONS */
   
    this.grayscale = function( val )
    {
        val = val || 0;
        if (val < 0){ val = 0; }
        if (val > 255) { val = 255; }
       
        return (val << 16) | (val << 8 ) | val;
    }
   
    /* PRIVATE FUNCTIONS */
   
    function limit( val, lowerLimit, upperLimit )
    {
        if (val < lowerLimit){ return lowerLimit; }
        if (val > upperLimit) { return upperLimit; }
        return val;
    }
       
    /* PUBLIC GETTER FUNCTIONS */
   
    this.__defineGetter__("value", function()
    {
        return (_red << 16) | (_green << 8 ) | _blue;
    });
   
    this.__defineGetter__("red", function()
    {
        return _red;
    })
   
    this.__defineGetter__("green", function()
    {
        return _green;
    })
   
    this.__defineGetter__("blue", function()
    {
        return _blue;
    })
   
    /* PUBLIC SETTER FUNCTIONS */
   
    this.__defineSetter__("value", function(val)
    {
        _red  = val >> 16 & 0xFF; // red
        _green  = val  >> 8 & 0xFF; // green
        _blue = val & 0xFF; // blue
       
        _value = val;
    })
   
    this.__defineSetter__("red", function(val)
    {
        _red = val;
        _red = limit( _red, 0, 255 );
    })
   
    this.__defineSetter__("green", function(val)
    {
        _green = val;
        _green = limit( _green, 0, 255 );
    })
   
    this.__defineSetter__("blue", function(val)
    {
        _blue = val;
        _blue = limit( _blue, 0, 255 );
    })
   
    /* PRIVATE VARIABLES */
    var _value = color;
    var _red;
    var _green;
    var _blue;
   
    /* PUBLIC VARIABLES */
    this.value = _value;
   
};
 

With this javascript class, you could use it like this:

var color = new nl.stroep.utils.Color(0xFFCC00); // define orange.
color.green = 0; // remove green.. now it is red..
color.blue = 255; // add some blue.. now it is purple..
alert(color.value.toString(16)) // alerts FF00FF and that is purple.
 

Hope you enjoyed this article. Feel free to share or comment.


Viewing all articles
Browse latest Browse all 2

Trending Articles