02
 
 
03

March 30, 2010

Proper Javascript Classes

Filed under: CodeAlex @ 5:59 pm

Javascript is an odd language, especially if you are used to programming in languages like PHP. For example, take a look at how you would create a parent class in PHP followed by a child class that inherits from it:

<?PHP
    // A simple class in PHP
    class Footware
    {
        public $color;
        public $size;
 
        function __construct($color, $size)
        {
            $this->color = $color;
            $this->size = $size;
        }
 
        function showColor()
        {
            echo $this->color . "<br/>\n";
        }
    }
 
    // Another class that inherits from Footware
    class Boots extends Footware
    {
        public $style;
        public $laces;
 
        function __construct($color, $size, $style, $laces)
        {
            $this->color = $color;
            $this->size = $size;
            $this->style = $style;
            $this->laces = $laces;
        }
 
        function showUse()
        {
            switch ($this->style) {
                case 'Steel Toed': $alert = 'Used for work';
                    break;
                case 'Cowboy': $alert = 'Used for line dancing';
                    break;
                case 'Fashion': $alert = 'Used for looking good';
                    break;
                default: $alert = 'Not sure what you would use these boots for';
            }
            echo $alert . "<br/>\n";
        }
    }
 
 
    $myShoes = new Footware('Tan',11.5);
    $myBoots = new Boots('Red', 11, 'Cowboy', 0);
 
    $myShoes->showColor();
    $myBoots->showColor();
    $myBoots->showUse();
?>

Classes are clearly defined, both visually and functionally. Inheritance is also easy to see and implement. Now take a look at the Javascript implementation of the PHP code above:

<script style="text/javascript">
 
    // Parent class definition
    function Footwear(sColor, fSize) {
        this.color = sColor;
        this.size = fSize;
    }
 
    // Use prototype to add methods
    Footwear.prototype.showColor = function () {
        alert('Color is: ' + this.color);
    }
 
    // End of the parent class
 
 
    // Child class definition
    function Boots(sColor, fSize, sType, iLaces) {
        // inherit properties from the parent class
        Footwear.call(this, sColor, fSize);
 
        this.style = sType;
        this.laces = iLaces;
    }
 
    // ...and use prototype chaining to inherit methods
    Boots.prototype = new Footwear();
 
    // Add more methods afterwards
    Boots.prototype.showUse = function () {
        switch (this.style) {
            case 'Steel Toed': alert('Used for work');
                break;
            case 'Cowboy': alert('Used for line dancing');
                break;
            case 'Fashion': alert('Used for looking good');
                break;
            default: alert('Not sure what you would use these boots for');
        }
    }
 
    // End of the child class
 
 
    var oMyShoes = new Footwear('Tan', 11.5);
    var oMyBoots = new Boots('Red', 11, 'Cowboy', 0);
 
    oMyShoes.showColor();
    oMyBoots.showColor();
    oMyBoots.showUse(); 
 
</script>

This is just one way to do it in Javascript but in general this is the best approach. Essentially what your doing is creating the class in two steps, a constructor portion (the function ClassName (param) portion) which contains all your properties, followed by a prototype section which houses all your methods.

While visually, this hybrid approach, makes a class look like it’s not encapsulated, rest assured it is. This method also gives you single parent inheritance, good memory usage, and fewer unexpected behaviors vs using just a constructor paradigm (good if you need multiple inheritance), or a prototype method by itself.

March 24, 2010

Javascript Closures

Filed under: CodeAlex @ 12:27 pm

If you’re wondering what a closure is, or how to use one, you should first understand scope. As an example, whenever you call a function, you expect it’s variables to die once the function ends. All it’s variables are limited in scope to the function, which is how you normally want it. To illustrate, let’s start with a typical javascript version of a class:

<script type="text/javascript">
 
function anObject() {
    this.publicVar = 'Accessible!';                // A public variable
    var privateVar = 'Not directly accessible...'; // A private variable
 
    var privateMethod = function() {
        // A private method
        alert('Can\'t call me directly either!');
    }
 
    this.publicMethod = function(param) { 
        // A public method
        this.publicVar += param;
    }
 
    this.accessPrivate = function() {
        // A privileged method
        alert(privateVar);
        privateMethod();
    }
}
 
newInstance = new anObject();
 
alert (newInstance.publicVar);
newInstance.publicMethod(' Modified by publicMethod.');  // Let's change the public var
alert (newInstance.publicVar); // Test to see if publicVar changed...
 
 
alert(newInstance.privateVar); // Undefined, You can't show private variables!
 
// Let's see if we can get at the privateMethod
try {
    newInstance.privateMethod();
}
catch(err) {
  alert("You can't get at the privateMethod directly. Let's try another way");
}
 
// Now try with a privileged method
newInstance.accessPrivate(); 
 
</script>

Now here’s a closure. At first brush, it seems to operate like a class but it’s quite different. Here you have a single object “aCat” that’s equal to a function. The (); following the function, tells javascript, to execute the function the second it’s parsed. So in a nutshell, “aCat” will equal whatever the function returns, and in this case it’s a collection of functions. Here, what’s returned is what creates the closure. Those functions are granting you access to the variables that have been closed over when the parent function ended and returned.

<script type="text/javascript">
 
var aCat = function() {
   // A bunch of private variables and functions
   var miceCaught = 1;
   var currentActivity = 'sleeping';
   var changeActivity = function(action) {
      alert('I was ' + currentActivity +", now I'm" + action);
   }
 
   return {
      /**
       * Here we are creating the closure.
       * Returning methods to access the
       * closed private variables.
       **/
      showMiceCaught : function () {
         alert(miceCaught);
      },
 
      catchMouse : function() {
         miceCaught++;
      },
 
      changeActivity : function(action) {
         changeActivity(action);
      }
 
   }
}(); // Here we tell javascript to run the function immediately
 
// We can now access the closed over variables and functions
aCat.showMiceCaught();
aCat.catchMouse();
aCat.showMiceCaught();
aCat.changeActivity('playing');
</script>

Rather than just being pedantic, closures do have at least one very useful function. Keeping the global namespace lean.

You create lots of functions, and global variables when you create your library, but each time you declare a function or variable, you increase the risk that you’ll have a collision with another library your using. A closure on the other hand gives you encapsulation. Creating all your global elements your library needs in a closure will help isolate your library from others.

As a simple example, lets say you want to show a message after the page loads. Normally you might do this:

<script type="text/javascript"> 
var msg = "Welcome!";
window.onload = function(){
    alert( msg );
};
</script>

What happens though if msg is already in use by another library? You’ve just clobbered it. So how do you get around this, and still use window.onload? Use a closure like this:

<script type="text/javascript">
(function(){
    var msg = "Welcome!";
    window.onload = function(){
        alert( msg );
    };
})();
</script>

Now javascript will execute the anonymous function immediately and tie the variable msg to the inner function. Later, after the page is loaded (including all the additional javascript code that might be there), the onload event is triggered, and your alert(msg) is run, BUT msg is kept out of the global scope. It’s truly private.

As a more sophisticated example, take a look at the source code for jQuery. Here the author has taken pains to not pollute the global namespace by using closures.

March 15, 2010

Why a logo doesn’t cost 5 dollars

Filed under: Useful StuffNatasha @ 3:27 pm

Here is a snippet from a great article written by a fellow designer from New York. To read an entire post please go to his blog.

“What Is A Logo? To understand what a logo is meant to do, we first must know what a logo is. A logo’s design is for immediate recognition, inspiring trust, admiration, loyalty and an implied superiority. The logo is one aspect of a company’s commercial brand, or economic entity, and its shapes, colours, fonts, and images usually are different from others in a similar market. Logos are also used to identify organizations and other non-commercial entities.

It makes me wonder why people… would even bother with a cheap logo design if a logo is meant to do all of these things?

Before I get onto comparing cheap VS professional logo design I want to talk to you a bit about SPEC work. “Spec” has become the short form for any work done on a speculative basis. For example, ‘You design this for me, and I will pay you if I like it’. This is not right.

To clarify, let’s create a scenario in another industry where SPEC work does NOT exist.

“I went for a dental check-up yesterday. After the dentist inspected my teeth, she suggested some work to prevent further tooth decay. I told her to go ahead, and if the dental work was satisfactory, I’d be more than happy to pay. She responded that she wouldn’t be able to do that, because she normally provides a service when a fee is agreed upon up-front. I said I’d let her know after I checked in with other local dentists.”

This scenario happens in the design industry every day and is seen as very unethical as it is ruining the design industry. A designer should not have to invest time and resources with no guarantee of payment much alike a dentist or any other professional.

I do not want to go into this any further as much has been written about it but I would like to say please avoid design contests and spec work at all costs. Logo Design Contests are bad for your business. Period.

$5.00 (Cheap Logo Design)
Now that we have taken a look at the damage of Spec Work, let us now take a look at what quality you can expect from a logo in between the $5 to $200 bracket. The particular case I am looking at today is from a logo design contest that was held on Digital Point Forums.

The “brief” for the logo design project was “Make a logo for the site ‘Spela Piano’. The meaning of that is Play Piano. This is a site where our members can learn to play piano online.” Below you can see the responses from the contest, which one do you think won?

$2.50

Ask yourself these questions in regards to the logos above:

  • How many of the logos can you describe or remember?
  • Are these logos effective without colour?
  • Are they scalable?
  • Do they gain immediate recognition?
  • Convey the company’s personality, character or attitude?
  • Relate to your clients by conveying a feeling of familiarity and credibility?
  • Have association with quality and satisfaction?

I will leave these questions for you to decide.

Professional Logo Design

Professional Logo Design

Now compare these professionally designed logos and answer the same questions as above… See the difference?

Why are they so different? Professional logo designers have an actual design process that involves research, sketching, conceptualising, and reflection and this is why they do not charge $5.00.

The design process of a professional logo designer usually consists of:

  1. The Design Brief: They conduct a questionnaire or interview with the client to get the design brief.
  2. Research: They conduct research focused on the industry itself, on its history, and on its competitors.
  3. Reference: They conduct research into logo designs that have been successful and current styles and trends that are related to the design brief.
  4. Sketching & Conceptualising: They develop the logo design concept(s) around the brief and research. They use creativity and know how to design a logo.
  5. Reflection: They take breaks throughout their design process. This lets their ideas mature and lets them get renewed enthusiasm and receive feedback.
  6. Presentation: They then choose whether to present only a select few logos to the client or a whole collection.
  7. Celebration: They then drink beer or eat chocolate or sleep or start on next logo design. Or a combination.

On that note, did you know that the software to make the logo is $700 in itself, let alone the computer that it has to be installed onto or the costs associated with the essentials… paper, ink and an internet connection.

Another 6 reasons why a logo should cost more than your lunch:

  1. A logo is the very first impression people get of your company.
  2. A logo needs longevity.
  3. A logo needs to be original.
  4. A logo should look professional.
  5. A logo should reflect the time and thought gone in to designing it.
  6. A logo is the starting point of your whole corporate image.”
 
7331 landscape station, berkeley, ca 94707, usa + 510 552 5567 < Berkeley / London > + 44 07525 203496 7 gloucester square, london, e28rs, uk
 
 
up arrow left arrow down arrow right arrow