August 2009 - Posts

Quinta Jardim da Serra weekend
Mon, Aug 31 2009 11:29

I’ve just returned from a really nice weekend on this lovely hotel. Bar services could be a little better and it’s not the easiest place to find, but the hotel is just great! Highly recommended if you’re looking for a nice place to say and relax for a couple of days. Here are some pics I’ve taken during my stay there. And now, it’s time to go back to vacations mode.

by luisabreu | with no comments
Filed under:
In operator vs hasOwnProperty property
Fri, Aug 28 2009 9:42

In yesterday’s post about the in operator, Bertrand mentioned that it would be interesting to show the differences between the in operator and the hasOwnProperty method defined on the Object “type”. As always, he’s right and I guess that I should write up a small post explaining the difference between these two.

Both of them check if a property belongs to an object, but there’s an important difference between them (besides the fact that in is an operator and hasOwnProperty is a property which references a function): the in operator will check the property name against the properties of the object +  the properties defined on the prototype object; on the other hand, the hasOwnProperty property will only check that name agains the properties of the object.

Here’s a really simple example which tries to show the main differences between these two:

var User = function(name) {
    this.name = name;
}
User.prototype.printInfo = function() {
    alert(this.name);
}
var user = new User("luis");
alert("printInfo" in user); //true :checks prototype
alert(user.hasOwnProperty("printInfo"));//false

From an usage point of the view, that’s really main difference between the operator and the method. Since hasOwnProperty is a property of object, there are a couple of things you should keep in mind:

  • every object has access to it (because all JavaScript objects end up “inheriting” the Object’s type prototype functions);
  • its use might be “compromised” by a redefinition of that property (which can be done by adding a property to the new object with that name or by changing the prototype’s hasOwnProperty property to a new value – which, btw, could even be a non function value!)

And that’s it for now. Keep tuned for more on JavaScript.

by luisabreu | with no comments
Filed under:
Avoiding global namespace pollution: using “namespaces”
Fri, Aug 28 2009 9:23

Another neat trick used to avoid global namespace pollution is the notion of “namespace”. As you might expect by now, JavaScript doesn’t really support the notion of a namespace. However, you can rely on the fact that it’s “free” to add properties to any object and that those properties might also be objects. In practice, this means that by creating object “hierarchies” you can simulate the traditional OO namespace concept fairly easily. Here’s a really simple example:

var LA = {};
LA.helpers = {
    sayHi: function(name) { alert(name); }
};
LA.helpers.sayHi("luis");

As you can see, you’re adding a global LA object which will “wrap” all the other utility members. This technique is used by all major JavaScript libraries in order to prevent the so called global namespace pollution.

Keep tuned for more on JavaScript.

by luisabreu | 1 comment(s)
Filed under:
Using anonymous functions to avoid global namespace pollution
Thu, Aug 27 2009 13:02

I guess that you’ve written code like this in the past:

var user = document.getElementById("name");
var msg = "Hello, " + user.value;
alert(msg);

I can tell you that I’ve written several lines of code that resemble the previous snippet in the past. However, you should avoid it whenever possible. The main problem with it is that you’re polluting the global namespace and that is something you shouldn’t do.

In these cases, there’s really a simple strategy for avoiding this unneeded pollution: we can take advantage of anonymous functions! Here’s how I’d write the previous snippet:

(function() {
    var user = document.getElementById("name");
    var msg = "Hello, " + user.value;
    alert(msg);
})();

The syntax might seem awkward at first, but if you concentrate, you’ll see that it’s really simple. We define an anonymous function and execute it in place. (notice that the statement must end with the braces so that it is interpreted as a function invocation).

And that’s it for today. Keep tuned for more tips on JavaScript.

by luisabreu | with no comments
Filed under:
The in operator
Thu, Aug 27 2009 10:13

Even though you’ve might have been writing JavaScript code for some time, chances are that you haven’t heard about the in operator. However, this changes when you’re asked about the for( … in …). The fact is that most people know that there’s a for(… in …) statement but don’t know that you can use the in operator outside a for loop.

What does this operator do? It will simply check if an object has a specific property. Here’s a really simple example which checks if an object supports the “name” property:

var User = function(name, age) { 
    this.name = name;
    this.age = age;
}
var propName = "name";
var user = new User("luis", "33");
alert( propName in user);

The in operator expects two operands: on the left side, it expects a string or a numeric expression which will be checked against the object present on its right side. You can also apply this operator with arrays. However, in this case you’ll only be able to check supported indexes. Here’s an example:

var names = ["luis", "john", "peter"];
alert("peter" in names);//false
alert(2 in names);//true

Here’s a resume of what this operator returns:

  • false for a non existing property or for a property which has been deleted (don’t forget that we can remove properties from an object through the delete operator);
  • true for existing properties, even though those properties might have been set to undefined.

You’re probably wondering if this operator is that important. I confess that I haven’t used it much, but I do find it useful in certain scenarios. For instance, Douglas Crockford has used it in his helper functions that support classical inheritance.

by luisabreu | 4 comment(s)
Filed under:
“Static” methods
Wed, Aug 26 2009 15:24

Today I was discussing some JS stuff with Nuno on twitter and I noticed that I still haven’t talked about“static” methods in JavaScript. We’ve learned several important things about functions. We’ve already seen that they are objects and that they can be used as constructors. We’ve even seen that they can me used as “instance” methods of your new objects. In this post, we’ll see how to create “static” methods.

Static methods are defined as properties of a function which (supposedly) is used as a constructor of a type. Here’s a small example:

var User = function(name, age) {
    this.name = name;
    this.age = age;
}
User.isEmpty = function(user) {
    return user == null ||
           user.name === null ||
           user.name === undefined ||
           user.name === "";
}
var user = new User("luis");
alert(User.isEmpty(user));

As you can see, the only way to access the isEmpty “static” method is through the User function. Calling these functions “static” methods is just a reminiscent of traditional OO programming. In fact, they’re nothing more than properties of the User function (this does make sense when you recall that functions are objects too!). The biggest advantage of using this “hack” is that you won’t be polluting the global namespaces with new functions (something which is really important if you’re building reusable libraries).

And that’s it. Keep tuned for more on JavaScript.

by luisabreu | with no comments
Filed under:
The semicolon bug
Wed, Aug 26 2009 13:52

Since I’ve started blogging about JavaScript, I thought that it would be ok to share with you one of the most embarrassing bugs I’ve introduce in a code base. Now, when I look back, I do find it funny, but I can tell you that I didn’t laugh about it at the time. The code is really simple, but I guess it shows why I started putting braces on the opening line…

function doSomething(number) {
    //do some very interesting stuff here
    //return object
    return   
    {
        x: number + 1
    };
}    
var a = doSomething(1);
alert(a);

Really innocent, right? Unfortunately, it returns undefined instead of the literal object I was trying to build. Btw, this will only happen when the returned object only has one property. If you had more than one, then you’d be getting a parsing error (in JavaScript, it’s common to use anonymous objects for passing data around and it’s not uncommon to fill only the “used” fields).

I guess that if I had read the spec I would have found that JavaScript will automatically insert the ; after certain statements. Here’s what the 1.3 spec says about this topic:

Certain ECMAScript statements (empty statement, variable statement, expression statement, do-while statement, continue statement, break statement, return statement, and throw statement) must be terminated with semicolons. Such semicolons may always appear explicitly in the source text. For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.

I guess that the moral of the story is that in JavaScript, the C K&R style should be used always.

P.S.: a final note to say that I’ll be receiving Douglas Crockford’s book in the next couple of days. That means I’ll be learning a few more tricks to share with you :)

by luisabreu | 7 comment(s)
Filed under:
Currying in JavaScript
Wed, Aug 26 2009 12:41

One interesting thing we can do in JavaScript is currying. It allows us to produce a new function by combining a function and an argument. To introduce the concept, we’ll start with a really simple example. Take a look at the following code:

function multiplier(b) {
    return function(a) {
        return a * b;
    }
}
var double = multiplier(2);
var result = double(5);

The multiplier function might seem weird at first…it receives an argument and returns an anonymous function which expects another argument.  Notice that invocating multiplier will only return a function which much be called for you to “get” the final result. In practice, multiplier is pre filing one of the arguments used by the internal anonymous function. As you can see, currying relies on JavaScript’s closure support. Btw, there really isn’t any restriction in the  “depth” of functions you can curry.

I guess that we all agree that using this approach for such a simple scenario is really overkill. However, currying does come handy in the “real world”. For instance, take a look at the following code (heavily borrowed from this John Resig’s post):

Function.prototype.partial = function(ctx) {
    var context = ctx;
    var that = this; //references "current" function
    var args = null;
    if (ctx.constructor === String) {
        context = window;
        args = Array.prototype.slice.call(arguments);
    }
    else {
        args = Array.prototype.slice.call(arguments, 1);
    }
    return function() {
        var arg = 0;
        var passedArgs = args.slice();
        for (var i = 0; i < passedArgs.length && arg < arguments.length; i++) {
            if (passedArgs[i] === undefined) {
                passedArgs[i] = arguments[arg++];
            }
        }
        return that.apply(context, passedArgs);
    };
};
var div1 = document.getElementById("div1");   
var clickBinder = div1.addEventListener.partial(div1, "click", undefined, false);
clickBinder(
    function() {
        alert("Howdy2!")
    });
clickBinder(
    function() {
        alert("Howdy!")
    });

What’s going on here? The idea is to use a simple function call to bind a method to a click handler of a specific element. And to do that…yes, you’ve guessed it: we’ll be using currying :) Before looking at the code, it’s important to understand that we’ll be using addEventListener to subscribe to events (it expects three parameters and it’s not defined in IE :( )

The first thing we’re doing is expanding the Function object so that it has a new partial method. I’ve opted for using a named parameter on the partial function (ctx) to make it explicit that the function relies on an object that will be used as the context of a future method call. Even though that isn’t required, it might come in handy if you want to update the context used from within the event handler and make it point to a specific object (I guess that the consensus is making it reference the DOM element responsible for the event). We could have reduce the initialization code quite a bit by saying that the top function should always receive a reference to the context that will be associated with the event handler.

We introduce the that variable because we need to access the function that is being invoked from within the inner function(remember that this is broken within inner functions and that we need to save the this reference when we need that object from within the inner function). Another thing the top partial method does is transform the arguments parameter into a real array, discarding the 1st parameter when it doesn’t reference a DOM element.

In this case, we’re just checking the type of the parameter by seeing if it’s a string (we’re relying on the [DOM element], “event name”, function, capture convention for the parameters that can be passed to the partial method). When that happens, we’ll be using the window object as the context associated with the execution of our handler.

The inner (returned) function looks a little bit strange at first sight. The first thing it does is clone the initial arguments passed to the top function (cloning is needed because we want to be able to use this helper for setting up several handlers. Without cloning, we would only be able to set up one handler because after the first call there wouldn’t be any undefined values – more about this in the next paragraphs).

After doing that, it searches for undefined values in the cloned array. Those parameters will be updated by the values passed when you call that inner function. Again, this relies in convention and assumes that everyone will use undefined for parameters that will be passed in “future calls”. The easiest way to understand how this work is to look at the clickBinder definition and usage:

var div1 = document.getElementById("div1");   
var clickBinder = div1.addEventListener.partial(div1, "click", undefined, false);
clickBinder(
    function() {
        alert("Howdy2!")
    });

We’re passing four parameters to partial. Notice that we’re passing undefined to the third one. What we’re saying here is that the clickBinder caller is responsible for passing a valid value to that parameter. And that’s why the clickBinder calls shown pass an anonymous function. The loop in the inner function will replace the initial undefined value with this anonymous function. I hope I haven’t gone too fast, because we still need to understand the last line of the inner function:

return that.apply(context, passedArgs);

As you probably recall from a previous paragraph, the that variable captured the context of the top function call. It’s important to keep in mind that partial is expanding the Function object (it was added to the prototype object).

This means that the captured context will reference the function that is being accessed, ie, that will reference the addEventListener function itself. And now everything should be clear: the inner function will update the “missing” parameters with the new values and will make sure that this points to the context you’ve specified when you called partial. After having all this info, it will simply call addEventListener and hook up the function you’ve passed with the specified event.

As you can see, currying does allow several interesting scenarios. At the beginning, it does make your head hurt…ah, who am I trying to fool? In most cases, it will always make your head hurt, but you can expect lots of improvements in your JavaScript code when you use it well.

And that’s it for this post. Keep tuned for more in JavaScript.

by luisabreu | 2 comment(s)
Filed under:
Using the || initialization trick
Wed, Aug 26 2009 10:55

Suppose you’ve got a function and you expect it to receive some optional parameters. In these cases, you’d like those optional parameters to be initialized with a predefined value. Can we do that in Javascript? Yes, we can and all we need is to use the || operator. The following snippet should make this point clear:

function changeTextColor(color, elem) {
    elem = elem || document.body;
    elem.style.color = color;
}

As you can see, we expect two parameters. The initial check tries to ensure that elem points to a valid HTML element. It’s that simple and there really isn’t much more to say about it. Keep in mind that you shouldn’t get too fancy with this kind of tricks. For instance, I recall that a a colleague of mine which was getting started with JavaScript tried to be  a little too smart and wrote the following code:

elem = ( elem && elem.style) || document.body;

it seems good, right? The problem is that elem && elem.style will return elem.style! Was he right in performing the check? Yes, he was, but he did it in the wrong place. If you want to be that clever, then you’d better understand how && and || work. Btw, here’s a revised version of the previous method which checks for the style object before setting its color property:

function changeTextColor(color, elem) {
    elem = elem || document.body;
    if (elem.style) {
        elem.style.color = color;
    }
}

Keep tuned for more on JavaScript.

by luisabreu | 1 comment(s)
Filed under:
=== vs ==
Tue, Aug 25 2009 11:15

There are still lots of guys that don’t know that JavaScript has the === operator. The truth is that you should always use this operator instead of relying on the == operator. Btw, and since we’re talking about comparison operators, there is also a !== operator that should be used when you need to test that two values are different. The main difference between these operators is that the == and != will use type coercion when the operands are of different type (if both operands have the same type, then they both work the same way).

Ok, so what’s wrong with type coercion? The problem is not type coercion per si, but the rules that are used. For instance, take a look at the following snippet:

var option1 = 0 == ''; //true
var option2 = '' == '0'; //false

In my opinion, the results are not intuitive. In fact, there are so many rules that come into play here, that I’ve given up on using this operator (the only times you’ll see me using it is when I haven’t used JS for a while and the old C# habits come into play…but after 1h of JS, everything starts coming back and I go back to my old === and !== operators). If you don’t believe me, then take a look at the following paragraph which was taken from the spec:

If Type(x) is the same as Type(y), then
a. If Type(x) is Undefined, return true.
b. If Type(x) is Null, return true.
c. If Type(x) is Number, then
i. If x is NaN, return false.
ii. If y is NaN, return false.
iii. If x is the same number value as y, return true.
iv. If x is +0 and y is -0, return true.
v. If x is -0 and y is +0, return true.
vi. Return false.
d. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions). Otherwise, return false.
e. If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false.
f. Return true if x and y refer to the same object. Otherwise, return false.

If I’m not mistaken, there are at least 10 rules, each with several options. Can anyone blame me for simply not caring about this operator?

by luisabreu | 4 comment(s)
Filed under:
JavaScript and closures
Mon, Aug 24 2009 13:42

In the previous post, we’ve seen how to improve the quality of the OO code by using privileged methods. As I said at the time, that feature is only possible because JavaScript has closures. Closures let inner functions access variables defined in the outer enclosing function after that outer function has terminated.

This is a really powerful feature and allows several interesting scenarios (as we’ve seen in the previous post). For instance, take a look at the following code which shows a delayed alert message:

function showDelayed(msg) {
    setTimeout(
        function() { alert(msg); },
        300);
}
showDelayed("Hi!");

If you run the code, you’ll notice that the alert message shows the correct message and runs after showDelayed has ended. This happens because the inner function is able to reference the parameter that was passed to the method. Notice that the inner function doesn’t access a copy of the parameter; it does access the parameter itself. This is important and means that you should take some care when working with variables defined on the enclosing function so that you don’t end up “suffering” from side effects. Don’t believe me? Ok, let’s run a small experience… Start by adding several divs to your page:

<div>1</div>
<div>2</div>
<div>3</div>

And now add the following script that should be run when the DOM is ready (I know that it might be hard, but forget that JQuery exists for a moment or two):

function setUp() {
    var elems = document.getElementsByTagName("div");
    for (var i = 0; i < elems.length; i++) {
        elems[i].onclick = function() {
            alert("clicked on div " + i);
        };
    }
}
setUp();

The idea is that clicking the div should pop up an alert message showing the current position of the div. Unfortunately, that won’t happen and you’ll always get 3. Why? it’s simple: notice that the handler references the i variable defined on the outer enclosing function. Chances are that you’ll only click one of the divs after the for loop has ended. When the loop ends, i will be equal to 3 and that’s why clicking on any div will always yield 3.

The solution is to build a function which receives the value of i and executes immediately (this will end up “copying” the value of the outer i). However, we do need a function for the click handler, so we’ll need to return one from within our (now!) outer function. The following snippet should make this point clear:

function setUp() {
    var elems = document.getElementsByTagName("div");
    for (var i = 0; i < elems.length; i++) {
        elems[i].onclick = function(pos) {
            return function() {
                        alert("clicked on div " + pos);
                    }
        }(i);
    }
}

And that should return you the correct positions of each div. Notice that this is also a good illustration of defining and immediately calling a function (note that the function(pos) is being defined and immediately invoked on the spot – notice the use of () before the ;).

Closures are an important topic in JavaScript programming. You might not understand them right away, but I can tell you that when that happens you won’t go back and you’ll wonder how you managed to write code without them. Keep tuned for more on JavaScript.

by luisabreu | 1 comment(s)
Filed under:
Has ASP.NET really left the track?
Mon, Aug 24 2009 12:12

Hannes Preishuber has a post which asks if ASP.NET has left the track? It seems like Hannes is bashing the team for not improving the platform since the 2.0 release. I agree with this idea, though not with the specifics. In fact, in all the web apps I’ve worked until now, I’ve only used a couple of ASP.NET server controls. I’ve found most of them useless since I’ve ended up needing much more control over the generated HTML.

In fact, I’m not sure if I’d want the team to waste more time with ineffective controls. I’d really prefer that they would update the core infrastructure instead. For instance, my friend Paulo has already made several useful suggestions on connect which are way more important than getting more controls…

by luisabreu | 5 comment(s)
Filed under:
“Improving” the quality of the OO code
Mon, Aug 24 2009 11:57

In the latest posts, we’ve been talking about functions and on how we can use them to construct objects. One of the things OO purists have probably noted is that all the OO code we’ve written is public. Let’s reuse our previous User class (improved by the use of prototype to extend the object’s methods):

function User(name, address) {
    this.name = name;      
    this.address = address;
}
User.prototype.sayHi = function(){
    alert( this.name + "-" + this.address);
}
var user = new User("luis", "funchal");
user.sayHi();

If you load the previous “type”, you’ll notice that nothing prevents you from access the name field. There are cases when we don’t really want to allow that. For instance, suppose that we need to perform some checking before setting the name. With the current code, that is not possible! To solve this, we might start by adding a getter and setter methods:

function User(name, address) {
    this.name = name;      
    this.address = address;
}
User.prototype = {
    sayHi: function() {
        alert(this.name + "-" + this.address);
    },
    setName: function(name) {
        //do some stuff here before setting the name
        this.name = name;
    },
    getName: function() {
        return this.name;
    }
}
var user = new User("luis", "funchal");
user.setName("Luis");
user.sayHi();

This is better, but it still doesn’t solve all our problems. The main problem is that the name field is still “public” and that means that anyone who is consuming our “class” might access it. If you recall  a previous post in scopes, then you know that variables declared within a function can only be accessed within that function’s body. Lets update our code so that it uses function variables instead of public fields:

function User(name, address) {
    var _name = name;
    var _address = address;
    this.setName = function(name) {
        _name = name;
    };
    this.getName = function() {
        return _name;
    }
    this.setAddress = function(address) {
        _address = address;
    };
    this.getAddress = function() {
        return _address;
    }
}
User.prototype = {
    sayHi: function() {
        alert(this.getName() + "-" + this.getAddress());
    }
}
There are several changes here:
  • We had to add getters and setters to all the “fields” and they need to be declared within the constructor;
  • these getters and setters and known as privileged methods (to the best of my knowledge, this term was coined by Douglas Crockford). Privileged methods are public but they can still access those local constructor variables;
  • the sayHi method had to be updated to use the setter and getters because it can’t see the _name and _address fields due to the way scope works in JavaScript.

Notice that “privileged” methods can only be added to objects at construction time (unlike public methods, which can be added at any time).

Even though this will give you some insurances regarding the state of your object, you should use this technique with care. The main problem here is that you’re increasing the memory footprint of your object because the getter and setters methods aren’t shared between all instances of that “type” (notice that will only happen to methods you add to the prototype object). You’ll have to weight the pros and cons of this technique before you start using it everywhere.

In my (limited) JavaScript experience, I haven’t been using this approach much. Instead, I’ve been using a convention based approach (with public fields and *special* methods) and it has been working ok until now.

Before wrapping up, it’s important to mention that you can only use privileged methods due to closures. Closure is an important JavaScript topic and we’ll return to it in the next post. Keep tuned for more on JavaScript.

by luisabreu | 2 comment(s)
Filed under:
Function invocation in JavaScript - contexts revisited
Mon, Aug 24 2009 10:55

In the previous posts of the series, we’ve started looking at functions. Today we’ll pick up where we left and we’re going to take a deep look at function invocation. I guess that first thing we should understand is what happens when we call a function.

Invoking function X leads to the suspension of the current function so that control can be passed to that new function X. As we’ve seen in the previous post, all functions receive a special argument parameter which contains all the parameters. Besides that special parameter, there’s another one we’ve met when we introduced contexts in JavaScript functions: I’m talking about the this parameter.

At the time, we’ve seen that by default, the this parameter references the global object (which, in an HTML page, references the window object). You can test this by running the following code:

function user(name) {
    //this references global object
    this.name = name;
}
user("luis");
alert(window.name);

Running the previous snippet should lead to a message that shows “luis”.  The important thing to keep in mind here is that with this simple invocation pattern, the this reference will always reference the global object. This might (or might not) be problematic. Lets update the previous snippet so that it uses a helper method:

function user(name) {
    this.name = name;
    function addSomething() {
        return this.name + "++";
    }
    this.name = addSomething();
}
user("luis");
alert(window.name);

If you run the previous snippet, you should see the alert with “luis++”. Everything worked as expected, right? Lets make things more interesting, shall we?

I’m sure you remember (from the previous post) that we can use functions as constructors, right? Let’s do that. Here’s our new code:

function User(name) {
    this.name = name;
}
var user = new User("luis");
alert(user.name);

In this case, the function is invoked as constructor (notice that we’re using the new operator) and is responsible for creating a new object. Notice that this no longer references the global object. In fact, it references the “current” object and that’s why you’ll get the correct name when you pass user.name to the alert method.

We could probably improve our code by adding a helper method that prints the alert message. Here’s one possible option for doing that:

function User(name) {
    this.name = name;
    this.sayHi = function() {
        alert(this.name);
    }
}
var a = new User("luis");
a.sayHi();

Notice that the sayHi function is invoked as a member method of the object. This means that you can be confident that the special this variable references the “current” object and you’ll get a valid value for the name property. btw, the result would be the same if you added the method to the function’s prototype object (and for functions like sayHi, that’s where you should be “putting” your functions).

We’ve already met three invocation scenarios. There’s still one left and to understand it, we’ll need to modify our code. Let’s assume that we’ve got some complicated logic which is “packed” into a helper method and is responsible for performing the final initialization before the object is instantiated. Here’s some dumb code that simulates that:

function User(name) {
    this.name = name;    
    //do some other stuff
    function addSomething() {
        this.name = this.name + "++";
    }
    addSomething();
}
var a = new User("luis");
alert(a.name);

Since the helper code will only be used from within the constructor, we’ve opted for using an internal function (the advantage of doing this is that this function will only be callable from within the constructor). Since addSomething is internal, you’ll probably be thinking that this will reference the same object as the User’s this variable. Unfortunately, that doesn’t happen.

To understand why, you need to look at how the method addSomething is invoked. As you can see, it uses the first pattern we’ve seen in this post and we already know that in those scenarios this references the global object. What this means is that the addSomething ends up initializing the name property of the window object with the “++” value (instead of adding that value to the User’s name property). In these fairly simplistic scenarios, Javascript programmers will generally introduce the that variable for letting the addSomething access the correct context (you can think of this a general convention):

function User(name) {
    var that = this;
    this.name = name;    
    //do some other stuff
    function addSomething() {
        that.name = that.name + "++";
    }
    addSomething();
}
var a = new User("luis");
alert(a.name);

As you can see, the main difference relies on the that local variable which is reused by the addSomething method. Even though this approach works, what we’d really love is a way to change the context associated to the addSomething. And yes, JavaScript allow us to do that through a 4th function invocation pattern.

Take a look at the following code:

function User(name) {
    this.name = name;    
    //do some other stuff
    function addSomething() {
        this.name = this.name + "++";
    }
    addSomething.apply(this);
}

As you can see, by using the apply method we no longer need to introduce a local variable. The first parameter passed to the apply method will be used as the context from within the addSomething function. The apply method expects a second parameter: an array with the values that will be passed to the function. Since the function does not expect any parameters, we simply don’t pass anything when we call the apply method.

Besides the apply method, functions have a second method which allow us to set the context used by that function: I’m talking about the call method. The main difference between the two is that apply expects that the parameters you’re passing to be packed into an array, while call expects one or more parameters separated by comma. For instance, suppose we’re calling an add method. Here’s the code you’d be using with apply and call:

add.apply(context, [par1, par2, par3]);
add.call(context, par1, par2, par3);

As you can see, there’s more to function invocation than you might think of at first. And this concludes our deep dive into functions and contexts. Keep tuned for more on JavaScript.

by luisabreu | 3 comment(s)
Filed under:
Using functions as constructors
Mon, Aug 24 2009 10:08

In a previous post, we’ve already met an easy way of creating objects through literal objects (which I personally prefer to call anonymous objects). Unfortunately, there were some shortcomings to that strategy: things didn’t work quite well when we needed to add methods that should be used for specific types of objects.

Today we’re going to see how we can use functions as constructors. The idea is simple: we add a new function which defines the expected parameters and then we instantiate a new object by using the new operator.  Here’s a snippet which reuses our previous OO example:

var User = function(name, address) {
    this.name = name;
    this.address = address;
}
var user = new User("Luis", "Funchal");
alert(user.name + "-" + user.address);

If you run the previous snippet, you’ll see that you’ll get a message with the user’s name and address. Functions are really interesting objects! If you recall our previous discussion on the Object type, you probably remember that all objects have a prototype object. Since functions are objects too, they also have their own prototype object. This object has a special property called constructor which references the function itself. That means that the following line will always yield true:

alert(user.constructor === User);

The constructor property (it would be probably better to call it function because it does  reference a function) is really interesting and you can use it in fairly advanced scenarios. For instance, you can use it for emulating overloads (more about his in future posts).

Notice also that the function prototype object is also “linked” to the Object’s prototype object (you can easily check this by using the code I’ve shown in a previous post – don’t forget that expanding the Object’s prototype property is really a bad bad bad thing to do).

Now, since we’re building new instances from functions, it’s “safe” to expand the prototype with helper methods. In fact, this is one of the recommended approaches you should take when building new “types” in JavaScript. For instance, here’s a method that concatenates the name and address of a user:

User.prototype.sayHi = function() {
    return this.name + "-" + this.address;
}
var user = new User("luis", "funchal");
alert(user.sayHi());
The advantage of doing this is that the sayHi method will only be available to instances created through the User constructor. In other words, if you create another function constructor (ex.: Student), you’ll see that you won’t be having any sayHi method because that method was only added to the User’s prototype object. And that’s it. Keep tuned for more on JavaScript.
by luisabreu | 3 comment(s)
Filed under:
Ribeiro Frio Balcões Walk
Fri, Aug 21 2009 22:18

Today I’ve managed to do another walk. This time, it was a really short one, from Ribeiro Frio to Balcões. I’ve took some pictures and I’ve uploaded them to facebook.

by luisabreu | with no comments
Filed under:
1000 mark
Thu, Aug 20 2009 15:09

I was looking at my settings on msmvps.com and I’ve notice that I’ve hit the 1000 posts mark. Honestly, I never expected to reach that mark (nor was it an objective), but it seems like it happened…

1000mark

by luisabreu | with no comments
Filed under:
Functions in Javascript – part I
Thu, Aug 20 2009 14:31

Douglas Crockford says that the best part of Javascript is its implementation of functions. And I think that he’s absolutely right! The first thing you should keep in mind is that functions are objects in Javascript! The second interesting thing about functions is that they can be invoked (I guess that’s why they’re called functions, right?).

The simples way to create a function is through a function literal. Function literals start with the function keyword. Optionally, you can give it a name and define the expected parameters. All functions have a body delimited by curly braces. Here’s a really simple named function:

function sayHi(name) {
    alert(name);
}
sayHi("luis");

Even though you can keep introducing named functions, you’ll soon find out that this is not really a good idea. The main problem is that by adding definitions like the one in the previous snippet, we’re really adding methods to the global namespace and we’re increasing the chances of conflicts with other libraries (which leads to overwriting, not errors). The following snippet should show you why this is bad:

function sayHi(name) {
    alert(name);
}
function sayHi(name) {
    alert("hoho!");
}
sayHi("luis");

If you recall a previous post on scopes and contexts, then you’ll probably remember that functions are always associated with a context (which you can reference from within the function’s body by using the this identifier). Besides the this identifier, there’s also the arguments identifier which you can use to access the parameters that are passed to the function.

Notice that you wont’ get an error when the number of values passed to the function doesn’t match the declared parameters. The only insurance you have is that you can get all the values passed to the function through the arguments identifier. arguments also let us access the current function (arguments.callee) and the function that performed the current call (arguments.caller). The callee property is useful for recursion scenarios on anonymous functions. Look at the following example:

var factorial = function(number) {
    if (number === 0) return 1;
    return number * arguments.callee(number - 1);
};
alert(factorial(3));

Since we’ve opted for introducing an anonymous function, the only available option for invocating it is relying on the arguments.callee property. Since it points to the “current” function, we can use the () operator to invoke it and get the desired recursion behavior.

There’s really lots of stuff to write about functions, but we’ll leave it for future posts. Keep tuned for more on Javascript.

by luisabreu | 5 comment(s)
Filed under:
Objects and the prototype property
Thu, Aug 20 2009 14:01

In the previous post, we’ve started looking at objects. At the time, I’ve said that next post would be on functions, but after some thinking, I’ll be talking about the “hidden” prototype property. Besides “custom” properties specified through name/value pairs, all Javascript objects have a special property accessed through the prototype name. This property references the so called prototype object (which can be null!) and is  generally used in Javascript for supporting inheritance.

But we’re going too fast! Let’s start with something simple. As we’ve see, object literals let us create new objects by using a simplified syntax. That means that these two snippets are equivalent:

var user = {
    name: "luis",
    address: "funchal"
};
var anotherUser = new Object();
anotherUser.name = "luis";
anotherUser.address = "funchal";

The Object type has a prototype property that we can use to extend the type. To see when this is really useful, we need an example. For instance, lets say that we wanted to have a helper method for printing the user information. The simplest approach which doesn’t involve global functions would probably look like this:

var user = {
    name: "luis",
    address: "funchal",
    printInfo: function() {
        alert(this.name + "-" + this.address);
    }
};
user.printInfo();

If you run the previous snippet, you should see an alert message with the expected info. But what happens when we create a new “user” object? With the previous code, we’d have to repeat everything:

var anotherUser = {
    name: "luis",
    address: "funchal",
    printInfo: function() {
        alert(this.name + "-" + this.address);
    }
};

Can we do better? Yes, we can. We can use the prototype object to extend the Object type. Here’s how:

Object.prototype.printInfo = function() {
    alert(this.name + "-" + this.address);
};

And now we can go back to our first definition of user:

var user = {
    name: "luis",
    address: "funchal"    
};
user.printInfo();

And it works! Since literals are always created from the Object type, all variables of that type will be able to call the printInfo because we’ve expanded the original prototype of the Object type with that property (which, btw, points to a function). Notice that there are also some non desired “side effects”. For instance, the following snippet is correct but doesn’t make any sense in that context:

var somethingElse = {
    phone : '122-1111'
};
somethingElse.printInfo();

Things like this are one of the reasons why we tend to use functions to create new objects which have “custom” behaviors (more on that in future posts). Notice that all the "object types” (ex.: Object, Function, Array, etc) of Javascript have their own prototype which ends up being linked to the Object’s prototype property (in other words, Function has its own prototype property which is also linked to the Object’s prototype property!). We’ll be coming back to this topic when we talk about OO and functions. Keep tuned for more on Javascript.

by luisabreu | 5 comment(s)
Filed under:
Simple types and objects in Javascript
Thu, Aug 20 2009 12:27

When I first started working with Javascript, I was a little surprise to know that you’ve got two “basic” types in BLOCKED SCRIPT there are simple types and objects. Simple types are numbers, strings, bools, null and undefined. Everything else is an object.

Objects are associated with two interesting features in BLOCKED SCRIPT

  • unlike most OO languages, there really isn’t the concept of a class in Javascript. It does support (probably a better word would be emulate?) many of the OO concepts you find in a OO language. For instance, inheritance relies on the prototype property (more about this in future posts). Using it well is a must if you want to write Javascript code;
  • they’re “mutable” and can be seen as a container of properties defined by the pair name/value (they’re similar in features to what you get when you work with hashtables in.NET). Property names must be string and their values can be any Javascript value (except undefined because this value is used for identifying inexistent properties).

So, if there isn’t a class concept, how do you create new objects in Javascript? You’ve got two options here: you can create an object literal (which I tend to call anonymous object) or you can create a function that initializes the fields of an object. In this post, we’ll concentrate on looking at the basic features associated with object usage and we’ll only be using object literals.

An object literal is delimited by curly braces and contains 0 or more properties defined through name:value pairs. Take a look at the following snippet:

var user = {
    name: "Luis",
    address: "Funchal"
};

You’ll see that many developers delimit the name of a property with “ or ‘. You only need to do that if the name you’re using isn’t a valid Javascript identifier or if it is a reserved keyword. Accessing the value is really simple too. For starters, we can use the well-known . notation:

alert(user.name);

Or you can use the not so well known indexer syntax:

alert(user["name"]);

The . syntax is the most used approach and you’ll only see the indexer property being used in advanced scenarios (ex.: when you don’t know beforehand the name of the property) or when the name isn’t a valid Javascript identifier. Notice that the indexer syntax allows several interesting scenarios. For instance, the following snippet enumerates the properties of the user object:

for (var propName in user) {
    alert(propName + ":" + user[propName]);
}

The specs don’t mention anything about the order in which the fields are enumerated, so don’t take any dependencies on that. Accessing an inexistent property returns undefined:

alert(user.something);//undefined 

However, setting an inexistent property results in adding that property to the object. So, if the previous line of code was preceded by the next, it would return a valid value:

user.something = { msg: "Howdy" };

Btw, notice that the something property references another anonymous object (or, if you prefer the Javascript jargon, literal object). You can also remove an existing property from an object. To do that, we need to use the delete keyword. Try the following snippet:

user.something = { msg: "Howdy" };
alert(user.something);
delete user.something;
alert(user.something);

Running it will show you two alert messages: the first shows the info object and the second returns the undefined message. What I’m saying next won’t probably mean much now, but it’s important to remember that delete will only remove a property from the object if it exists (it won’t remove prototype properties!).

And I guess this wraps this post.  In the next post, we’ll keep looking at objects and we’ll talk about functions and their role in Javascript OO. Keep tuned!

by luisabreu | 4 comment(s)
Filed under:
More Posts Next page »