Setembro 2009 - Posts

Another cool JavaScript trick: memoization
30-9-2009 21:35

Memoization is one nice trick you can use to improve your JavaScript code. The idea is quite simple: in scenarios where you have “pure” functions, you can improve the total time of execution by saving the results of previous executions. I think that an example will help understand how things work. Let’s start by looking at how we might calculate the factorial of a number:

var factorial = function(num) {
    return num < 2 ? 1 : num * factorial(num - 1);
}

The previous function ignores negative numbers and will simply return one for any number that is smaller than 2 (you could improve the code by checking for negative numbers). The problem with this function is that you end up invoking the function several  times and you won’t reuse any of those results in future calls. For instance, if you invoke factorial(5) and then factorial(6), you won’t be able to reuse the results of the first call in the second call. Memoization helps in these cases! Here’s the updated code that uses memoization:

var factorial = function(num) {
    var results = [1, 1]; //0!===1! === 1
    var calculate = function(n) {
        if (results[ n ] === undefined) {
            results[ n ] = n * calculate(n - 1);
        }                
        return results[ n ];
    }
    return calculate;
} ();
alert(factorial(5));
alert(factorial(6));

(Once again, I’m not testing for negative numbers in order to keep things simple).

Most of the work is run by the inner calculate function. We wrap it up in an anonymous function so that we can reuse closures to keep the results array “private”. As you can see, calculate will always check for a value in the results array before performing a recursive calculate call.

To make it work, we need to return calculate (ie, we need to return a reference to the calculate function) from the anonymous function and we also need to execute the anonymous function in place (notice the () after the anonymous function definition!).

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

[Crossposted from http://msmvps.com/blogs/luisabreu]
por Luis Abreu | with no comments
Filed under:
The observer pattern in MS AJAX – part I
30-9-2009 9:22

Today we’ll keep looking at the new MS AJAX library (preview 5) and we’ll start looking at the observer pattern. Wikipedia defines the observer pattern like this:

The observer pattern (a subset of the asynchronous publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.

In practice, implementing the observer pattern means that the observable object needs to have methods that lets eventual observers subscribe or cancel their interest in receiving notifications. The observers must also implement a predefined interface so that the subject can notify them when there’s a change in its state.

In “.NET land”, the most common implementation of this pattern relies on events: the subject exposes a public event which might be handled by one or more observers. But how does it work in JavaScript land when you’re using MS AJAX? If you’ve been using MS AJAX for some time, you’ve probably noticed that it tries really hard (too hard, if you ask me!) to mimic .NET. And that’s why you’ve got those cute OO helpers (which loose some of its initial appeal when you start “understanding” JavaScript – interesting discussion, but we’ll that to another day), events which look and feel like .NET events, etc…

Hey, did you notice that? we’ve got events which look like .NET events…that means that we can follow a similar path for implementing the pattern in MS AJAX. Lets start thinking about our subject (that is, the object that is observed). Suppose we’ve got a simple object (student) which has two properties (name and address):

var student = {
    name: "luis",
    address: "fx"
};

Now, since we want it to be observable, we need to change its API so that it uses events. But which events will we expose? nameChanged? addressChanged? Both? And what will happen if we need to add more properties in the future? If you think about it, the best option is to generate a generic event which has info about the property which was changed. Lets call it propertyChanged event! If we want to fire the event, that means that we need to change our API so that it uses the getter/setter pattern for accessing the properties. Here’s the code we need for this:

var student = {
    _events: new Sys.EventHandlerList(),
    _name: "luis",
    _address: "fx",
    get_name: function() {
        return this._name;
    },
    set_name: function(name) {
        this._name = name;
        this._raiseEvent("name");
    },
    get_address: function() {
        return this._address;
    },
    set_address: function(address) {
        this._address = address;
        this._raiseEvent("address");
    },
    add_propertyChanged: function(handler) {
        this._events.addHandler("propertyChanged", handler);
    },
    remove_propertyChanged: function(handler) {
        this._events.removeHandler("propertyChanged", handler);
    },
    _raiseEvent: function(propName) {
        var handler = this._events.getHandler("propertyChanged");
        if (handler) {
            handler(this, new Sys.PropertyChangedEventArgs(propName));
        }
    }
};

(A couple of observations before going on. The first thing to notice is that I’ve opted for using a simple object. If you’d be thinking on reusing this custom ”type”, then you’d probably be better by creating a JavaScript “class” and “putting” the methods on its prototype object. The second thing you should notice is that a better implementation of the setter would start by comparing the new value with the existing one before updating the field and raising the corresponding event.)

With the previous code, we can now add as many observers as we want. Here’s some demo code:

student.add_propertyChanged(//add an observer
    function(sender, e) {
        alert("observer 1:" + e.get_propertyName());
    });
student.set_name("john");//event will be fired

You’ll always need code which looks like this for implementing this pattern in JavaScript. Nothing prevents you from writing this code with the current release of MS AJAX. Yes, it’s doable, but it still leaves a lot of boilerplate code to the programmer. The next release of MS AJAX will cut down this work by introducing the Sys.Observer object. The idea is really simple: instead of coding everything by hand, we can just rely on that object for “adding” the necessary methods to our object. To show you how easy it is, we’ll update the previous example so that it uses the new Sys.Observer class:

var student = {   
    name: "luis",
    address: "fx"
};
Sys.Observer.makeObservable(student);//"implement" observer pattern
student.add_propertyChanged(//add an observer
    function(sender, e) {
        alert("observer 1:" + e.get_propertyName());
    });
student.setValue("name”,”john");//event will be fired

Even though we didn’t add the add_porpertyChanged and setValue methods explicitly, the truth is that our student object does expose them! Those method were added by the “static” makeObservable method. Besides that method, it will also add others:

observer

As you know, JavaScript is a language where objects are dynamic and that’s why they’re easily expandable (you can simply add new properties to an object or to its prototype). The Sys.Observer object uses this feature to add the necessary methods at runtime, transforming any object into an observed object.

We won’t be talking about all the “observer methods” in this post (for instance, we’ll leave the beginUpdate/endUpdate method for a future post), but we can’t end the post without talking about setValue method. If you look at our first attempt of implementing the pattern, you’ll see that we’ve ended up adding a set_XXX method to our object because that was the only way we could intercept a property change.

When you’re thinking in a generic implementation of the pattern, you can’t really go on and dynamically add getters/setters to all the properties of the object. In this case, the best option is to add a single generic method and force every property change to go through it. And that’s why we’ve got a setValue method.

There are some downsides with using the Sys.Observer object. I guess that the worst is that you end up specifying the property name as a string when you need to update its value (and we all know how many times we get names wrong, right?). Anyway, I think that this is not enough for stopping you from using this feature.

Before ending, there’s still time for one additional note. Even though I’ve used a literal object in the samples I’ve shown, the current implementation of the “observer methods” (ie, the methods which are added to your object when you call the makeObservable method) also supports the getter/setter paradigm used by most OO classes implemented over the MS AJAX lib (in other words, before accessing the XXX property, it will try to access the set_XXX setter).

And that’s it for now. Stay tuned for more on JavaScript and MS AJAX.

[Crossposted from http://msmvps.com/blogs/luisabreu]
por Luis Abreu | with no comments
Filed under: ,
Variables are cheap; access to DOM tree is not
25-9-2009 15:08

 

One of the things people don’t do (most of the time) is use variables. For instance, here’s a snippet which shows some code which looks good:

function do1() {
    var time = (new Date).getTime();
    for (var i = 0; 
i < document.getElementById("content").childNodes.length;
i++) { var txt = document.getElementById("content")
.childNodes[i].innerText;
//do something } var end = (new Date).getTime() - time; alert(end); }

This codes works perfectly, ie, it will successfully go through all the child nodes of some element and it will get their text. The problem here is that using DOM for getting stuff is (kind of) expensive. On the other hand, variables are really cheap. What this means is that if you’re going to be using some element a lot, you should probably cache it in a local variable. Here’s an improved version of the previous function:

function do2() {
    var time = (new Date).getTime();
    var nodes = document.getElementById("content").childNodes;
    for (var i = 0; i < nodes.length; i++) {
        var txt = nodes[i].innerText;
    }
    var end = (new Date).getTime() - time;
    alert(end);
}

Yes, you end up writing more code. However, notice that we’re caching more aggressively here (ex.: the child nodes are cached and that means, for example, that we don’t have to go through the DOM during the for’s guard test). Oh, in case you’re asking, the answer is yes: we could still improve our code by caching the total count of child nodes and using that variable in the for’s guard.

Moral of the story: variables are cheap. prefer them over constant access to the DOM model.

[Crossposted from http://msmvps.com/blogs/luisabreu]
por Luis Abreu | with no comments
Filed under:
Simplifying the API of your JS methods
25-9-2009 14:45

If you’ve been using JavaScript for some time, I’m positive that you’ve seen JS methods which look like this:

function doSomething(address, 
methodName,
shouldThrowOnError,
successCb,
errorCb) { //code goes here }

In my opinion, this kind of API sucks. If you’re not seeing why, then suppose that all parameters are optional. When you only need to set the first parameter, things aren’t really that hard. Now, suppose you want to set the last parameter…with the previous API, you’ll need to pass default values for all the parameters and that really sucks, right? With the current API, here’s the code you’d need for setting only the last paragraph:

doSomething(null,
            null,
            null,
            null,
            function(err) {
                //handle error here
            });

Fortunately, there’s an easy way to solve this mess: we can use literal objects to “aggregate” the function’s parameters. Here’s the refactored API:

function doSomething(options) {
    //code goes here
    //access options.address here for address, etc.
}
doSomething( { 
        errorCb: function(err) {
            //handle error here
        }
});

As you can see, we need to change the API so that it expects an object which “aggregates” all the method parameters. The advantage of using this technique is that, now, consumers of your API can specify only the parameters that need to be set. This is really a simple change which makes life easy for the consumers of your library. In my opinion, you should use whenever possible. And that’s it for today.

[Crossposted from http://msmvps.com/blogs/luisabreu]
por Luis Abreu | with no comments
Filed under:
Stop copying blank lines in VS
25-9-2009 13:29

One of the things I end up doing sometimes in Visual Studio is copying blank lines. It’s not that I want to copy a blank line…it’s simply that I get interrupted while using ctrl+c/ctrl+v and end up messing things when I return to the desk. Since I’ve just ended up copying another blank line, I’ve lost a few seconds and opened the options window to see if I could control it from there. And yes, I can:

stopcopying

And there you go: no more blank line copying for me! (I’m blogging about this now because I’m currently using VS 2010 without resharper! If I had resharper, things would be much better :))

[Crossposted from http://msmvps.com/blogs/luisabreu]
por Luis Abreu | with no comments
Filed under: ,
No more notifyScriptLoaded needed
24-9-2009 21:02

I know that it’s been a long time since I’ve used ASP.NET AJAX (I think that I didn’t even realized that it had been so long since I’ve used in my day to day development). Today, I’ve just noticed that you no longer need to invoke the notifyScriptLoaded method to notify the end of the script loading:

if (Sys && Sys.Application) {
  Sys.Application.notifyScriptLoaded();
}

Yes, you no longer need to do this because now script loading completion is based on handling the DOM events (which vary, based on the browser :( ). Good news, without any doubt….

[Crossposted from http://msmvps.com/blogs/luisabreu]
por Luis Abreu | with no comments
Filed under: ,
The script dependency registration of MS AJAX
23-9-2009 14:53

I’ve finally started looking at the latest release of the ASP.NET AJAX library (preview 5). This version introduces several new features and I’ve thought I should write a couple of posts about it here. Today I’m going to talk about a feature I like to call “script dependency registration” (btw, it has been a long time since I’ve looked at/used the MS AJAX lib, so this feature might have been introduced in previous releases).

The idea is really simple: whenever you create your own script file, you’re supposed to register it and specify its dependencies (if there are any, of course). The best way to understand this is to look at an example. If you look at the MicrosoftAjaxTemplates file, you should see something like this:

Type._registerScript(
"MicrosoftAjaxTemplates.js",
["MicrosoftAjaxComponentModel.js", "MicrosoftAjaxSerialization.js"]);

The _register method expects two parameters:

  • a name that identifies the script. Typically, you’ll use the name of the JS file here, though there’s nothing from preventing you to use whatever name you want;
  • an array with a list of dependencies (notice that you’re supposed to pass the name of the dependencies).

What we’re saying in the previous snippet is that we’re registering the current file with the name MicrosoftAjaxTemplates.js and that it requires the MicrosofAjaxComponentModel.js and the MicrosoftAjaxSerialization.js entries for working properly.

If anyone is developing a component or writing code which requires the code available on MicrosoftAjaxTemplates, then you only need to register your new script and pass the “MicrosoftAjaxTemplates.js” value as a dependency:

Type._registerScript(
"MyComponent.js",
["MicrosoftAjaxTemplates.js"]);

As you can probably guess by now, the advantage of using this method is that you’ll get an exception if you try to use a script without loading all its dependencies.

If you’re creating scripts which *might* require specific features defined on a third party lib, then you probably will not want to use the Type._registerScript method.

For instance, you might use the DataView control’s ability to load data from a web service. To ensure that, you could always use the _registerScript method to force the loading of the JavaScript file which had the web service code. However, you might want to use only the basic features of the DataView control which don’t rely on some third party JS web service code. Since you’ve used the _registerScript to ensure scenario 1 (which required the web service JS code), you would end up adding unnecessary  code to the page (the web service code JavaScript file).

In these cases, there’s a better option: you should use the _checkDependency method instead of using the _registerScript method. Here’s an example of its usage (taken, again, from the MicrosoftAjaxTemplates.js file):

Type._checkDependency(
"MicrosoftAjaxWebServices.js",
"Sys.UI.DataView.fetchData");

As you can see, its use is slightly different from the _registerScript method. The _checkDependency method expects two parameters:

  • the name of the required dependency (supposed to be previously registered through the _registerScript method);
  • the name of the member/method that relies on tha dependency.

If the method can’t find the dependency registered, you’ll end up getting an exception which tells you something like “feature X requires script Y to work”. Pretty cool, right? (and way faster than taking a look at the error console and seeing that prop X isn’t defined, right?)

As you can see, you’ve got two options for checking dependencies: you should rely on the _registerScript method to register your script and enforce that all the third party JS lib files that support the basic features of your code are included in the page: on the other hand, you should use the _checkDependency method for ensuring that your component’s *optional* features work properly.

And this concludes the first post on the new MS AJAX lib. Stay tuned for more.

[Crossposted from http://msmvps.com/blogs/luisabreu]
por Luis Abreu | with no comments
Filed under: ,
The string concatenation tip
23-9-2009 12:23

One of the things you probably need to do is concatenate strings. I guess most of us simply use the + operator for that, right? I’ve seen lots of code which look like this:

var s = "Hello World";
for (var i = 0; i < 100000; i++) {
    s += "something else";
};

If you’re an experience JS developer, you’re probably thinking “oh my god"! what an awful piece of code…”. In case you’re wondering, the problem is that string concatenations are really expensive (because strings are immutable in JavaScript).

Now that you know you’ve got a problem, you can go on and search for solutions in the web. It won’t be long until you find the solution to this kind of problem. It’s really simple: you use arrays, push the strings into it through the push method and then you get the final string by calling the join method:

var s = ["Hello World"];
for (var i = 0; i < 100000; i++) {
    s.push("something else");
};

Ah, and now we can go home an relax because we’ve solver our string concatenation problems…really? hum, probably not…Today I’ve thought about using a simple test based on getTime to see how things work with the latest browsers. Here’s the script I’ve used:

function doIt1(){
    var time = (new Date).getTime();
    var s = "Hello World";
    for (var i = 0; i < 100000; i++) {
        s += "something else";
    };
    var end = (new Date).getTime() - time;
    alert(end);
}

function doIt2() {
    var time = (new Date).getTime();
    var s = ["Hello World"];
    for (var i = 0; i < 100000; i++) {
        s.push("something else");
    };
    var end = (new Date).getTime() - time;
    alert(end);
}

doIt1();
doIt2();

I’m not really an expert in benchmarking (I didn’t really run these lines several times for getting average values; instead, I’ve loaded the page several times in different browsers and annotated the values that were shown frequently for each browser). Here are the results I’ve got from running the previous snippet in several browsers (which might vary, of course):

  doIt1 doIt2
Chrome 3.0 16 5
FF 3 56 17
Opera 10 59 78
IE 8 25 71
Safari 4 40 4

As I said before, my main objective was to test the two techniques for concatenating strings (I’m not really interested in seeing which browser does string concatenation better). one more note of interest: before updating Opera to its latest release, the results were inverted (that is, it was slower to concatenate strings with the + operator than to use the array technique).

I guess that with the latest releases of browsers, it’s no longer safe to assume that the array+push strategy will improve our  string concatenation code. At least, not in IE and Opera.

I’d be interested in seeing if others get the same result as I did (regarding the concatenation speed in IE and Opera). If you do get the same results, then this means that improving string concatenation code might no longer a no brainer…

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

[Crossposted from http://msmvps.com/blogs/luisabreu]
por Luis Abreu | with no comments
Filed under:
Since closures are so great, I should use them whenever possible, right?
22-9-2009 12:48

A colleague of mine asked me this question this week and I thought that it would be a nice topic for a post. Don’t worry, I’ll be really quick about it!

Instead of saying no, I told him: it depends. “Depends on what?”, you ask. Well, one of the problem with closures is that it slows down your code. It’s relatively easy to understand why: closures also change the scope chain and that means more work for interpreter.

Besides that, closures have also been cataloged as one of the primary ways of leaking memory. The IE blog has an nice article on it, so I’ll simply redirect you to it. Notice that closures are not always bad (for instance, they allow several advanced scenarios – ex.: private fields in JavaScript). However, if you’re thinking in performance, you should probably try to reduce them to a minimum.

Btw, don’t just start removing closures if the app’s performance doesn’t match your expectations. Before doing that, you need to measure things (if you’re using lots of closures, you might start by measuring the time that operations which involve those closures take). Without that info, you’re not really sure on why something is taking lots of time.

[Crossposted from http://msmvps.com/blogs/luisabreu]
por Luis Abreu | with no comments
Filed under:
The with statement
21-9-2009 19:38

When I first noticed the with statement, I thought I had discover the “holly grail” of code simplification in JS. Take a look at the following snippet:

var student = {
    name: "luis",
    address: "fx", 
    hobbies: ["computers", "soccer", "tv"]
};
with (student) {
    name = "john";
    address = "lx";            
}

Well, everything looks good, right? And yes, in such a simple scenario, that is true. Now, the thing is that with will “augment” the current “context” with the object that you pass to it. In practice, and looking at the previous example, this means that you can use the name property of the student instance without using the instance variable name.

Before you go away, take an extra 30 seconds and look at the next snippet:

var name = "some other";
with (student) {
    name = "john";
}

If you run the previous snippet, you’ll see that within the with block, name refers to student.name and not to the global name variable. In practice, whenever you access an identifier from within a with block, the interpreter starts by checking if the object has a property with that name (that is, if obj.propName is not undefined). When that happens, the identifier references that object’s property. When that doesn’t happen, then you’ll be using a global variable (that is, if it exists).

As you can see, with can decrease the readability of your JS code (it may even introduce some bugs in your code). And from a performance stand point, it’s not looking good either because the interpreter needs to do extra work for changing the “context“ within the with block. I tend not to use the with statement in my JS code. In fact, I had completely forgotten it until that I’ve noticed today that it’s used in the JS code that is generated by the new templates “classes” introduced in preview 5 of ASP.NET AJAX (in fact, its side effects introduced a bug in the code I was writing and I didn’t even noticed, but I’ll leave that for a future post).

Stay tuned for more on JavaScript.

[Crossposted from http://msmvps.com/blogs/luisabreu]
por Luis Abreu | with no comments
Filed under:
Book review: Portugal, que futuro?
20-9-2009 15:32

Generally, I tend to review English written books in this blog. However, and since we’re on the verge of choosing a new PM for the next four years, I’m reviewing this fantastic book here and I’ll do it in Portuguese. In practice, this means that if you don’t understand Portuguese, you can safely skip this post.

O último livro de Medina Carreira (escrito em parceria com Eduardo Dâmaso) é explosivo! Eu comprei-o ontem (19 de Setembro) e consegui terminá-lo hoje (20 de Setembro). A introdução consiste na compilação de vários “ensaios” da autoria do Prof. Medina Carreira e o posfácio é totalmente escrito por Eduardo Dâmaso. Todo o restante livro é escrito em modo de entrevista, onde Medina Carreira responde a várias questões colocadas por Eduardo Dâmaso.

Medina Carreira analisa vários temas “quentes” da actualidade política Portuguesa. No seu tom “corrosivo”, identifica vários problemas que têm vindo a minar Portugal e que  levaram à estaganação em que nos encontramos. O livro não fala só de economia, apesar de essa ser uma área essencial que serve de suporte a todos os direitos e “benesses” que temos vindo a ter nos últimos anos.

Por exemplo, no capítulo dedicado à educação (apropriadamente intitulado de ‘Educação: “Magalhães” e mais o quê?’), apresenta uma análise detalhada sobre vários pontos incompreensíveis do nosso sistema educativo. Tal como Medina Carreira, também penso que a introdução de “Magalhães” nas nossas escolas não passa de espectáculo político! Ninguém nega a importância das novas tecnologias, mas eu tenho muitas dúvidas em relação a fornecer computadores a miúdos que ainda não sabem escrever nem contar direito. Existem ainda outras coisas mal explicadas…as tão apregoadas “Novas Oportunidades”…alguém acredita na formação que é dada nestes cursos? E as reformas da educação? Quem é que sai beneficiado com a tal “escola inclusiva”? Serão os alunos? Os Pais? E o estatuto dos alunos? Enfim, tudo áreas que contribuem para o aumento do descrédito do nosso ensino nos últimos anos…

Na minha opinião, capítulo mais importante será, provavelmente, o capítulo V. Nesse capítulo, Medina Carreira desmistifica completamente o  mito do “keynesianismo” e explica porque é que esse modelo não tem qualquer interesse nos dias de hoje para um país como Portugal. Depois de ler a resposta à pergunta da página 95, onde apresenta os principais princípios dessa doutrina, torna-se impossível não rir às gargalhadas quando ouvimos o nosso PM a justificar as grandes obras (como por exemplo, o TGV) com a doutrina de Keynes.

Antes de dar a nota final, aproveito para recomendar este livro a todos aqueles que se interessam com o estado da Nação. A minha nota para este excelente livro: 9.5/10.

[Crossposted from http://msmvps.com/blogs/luisabreu]
por Luis Abreu | with no comments
Filed under:
typeof vs instanceof
19-9-2009 14:26

Both of these operators are used to check if an object is of  specific type. So, which one should you use? The answer is: it depends…I guess that none of them is perfect. typeof will always return a string which identifies the “current type” (and this info is really useless most of the time). On the other hand, instanceof will always require two operands: and object and a “type”. It will only return true if the object is of that type. Here are a couple of examples:

var info = typeof { name: "luis" }; //"object"
var isObject = { name: "luis"} instanceof Object; //true

As you can see, one of the downsides of using typeof is that you end up comparing strings. But there are far worse things which can happen when you use this operator:

var info = typeof null; //"object"

ooppss…Yes, that’s right: typeof null returns object…not good, right? Nevertheless, there’s a simple solution for this kind of glitch: you can use the logical && operator and add an extra condition that tests for null (notice that I’m thinking in scenarios where you’re using an if to check for the current type of an object).

Unfortunately, there are other gotchas which might get you. Here’s another interesting snippet:

var info1 = typeof 10; //number
var info2 = typeof new Number(10); //object

If you’ve been doing JS for some time, this shouldn’t really surprise you, but the truth is that most people wouldn’t expect different results for the typeof in scenarios like the one I’ve shown. Yes, you can say that you’ll never use the Number type for creating a new number (I wouldn’t do that either), but what happens when you need to write a lib that will be used by other people?

I guess this means we can strike out typeof from our initial list of operators, right? That leaves us with the instanceof operator. When you start looking at it, everything looks good: you’re using types, so you shouldn’t get those nasty string errors (in the past, I’ve blown away simple typeof tests by missing a char on the string I was using on the comparison with the result returned from typeof). Here’s a quick example where instanceof works:

var info1 = [1,2,3] instanceof Array; //true
var info2 = new Array(1, 2, 3) instanceof Array; //true

the instanceof operator checks the prototype property to see if the passed constructor (second operand used with the instanceof operator) is the same as the one used for instantiating the first operand. btw, if you’re a JS developer for some time, you probably know that this won’t work when you use frames. And if you try that with numbers, you’re back to square one:

var info1 = 1 instanceof Number; //false
var info2 = new Number(1) instanceof Number; //true

(Just a small detour to remind you that numbers are primitive types and that means there’s no prototype property on them and that’s why instanceOf won’t really work with info1; on the other hand, info2 is an object and that’s why you’ll get the expected result when you use the instanceof operator).

The good news is that there was a guy that noticed that he could use the toString method of the Object prototype to get the correct description of the current object (I don’t know who introduced this technique first – for instance, I believe that JQuery has been using it since late 2008, though it uses it only in a limited scenarios and doesn’t slice the returned string). You’re back to strings again, but at least this works in all the previous scenarios. Here’s a quick example:

var info1 = 1; 
var info2 = new Number(1); 
var getClassName = function(type) {
    var prot = Object.prototype.toString;
    return prot.call(type).slice(8, -1);
}
alert(getClassName(info1));//Number
alert(getClassName(info2)); //Number

As you can see, using the helper getClassName will always return the string “Number” (even in those cases where you’re using a “primitive” number). After running a quick search, I was able to get a good compilation of values that are returned from this method. As you can see from that list, this is probably one of your best options for those scenarios where you need to know the type of an object.

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

[Crossposted from http://msmvps.com/blogs/luisabreu]
por Luis Abreu | with no comments
Filed under:
SpriteMe released
16-9-2009 22:34

I’ve just seen the announcement on Steve Souders’ blog (yes, I know: I’m late, but don’t forget I’ve been busy with network security training).

[Crossposted from http://msmvps.com/blogs/luisabreu]
por Luis Abreu | with no comments
Filed under:
JavaScript logical operators
16-9-2009 22:26

JavaScript has three logical operators: &&, || and !. We’ve already seen two posts on the ! and today we’ll wrap our discussion on logical operators by talking about the && and the || operators. Traditionally, you’ll hear something like this when these operators are presented:

The && operator returns true when all the conditions are true and the || operator will return true when at least one of the conditions is true.

hum…unfortunately, this is not really true in JavaScript. Ok, let me make this clearer: the previous definition is only true when both conditions are “true booleans”. I’ve already talked a little bit about the || operator in the past, so today we’ll concentrate most of our time in the && operator. Here’s a quick example which should make things quite clear:

var student = { name: 'luis' };
var result = student && true;
alert(result);

Yes, it’s another of my famous WTF snippets :)  we’re creating a student variable which holds a literal object. We then use the logical && on a complex expression and save that expression in a variable called result. What do you think the alert will show?

If you’re thinking “true”, then you’re correct. I can hear you thinking: “hey, but true is a boolean value and this guy has just said that the traditional definition of the && operator presented in one of the previous paragraphs isn’t right. has he been drinking or what?”. OK, let’s try a small change:

var result = true && student;

And now, what do you see in the alert message? If everything went ok, then you probably see the “[object Object]” string (which resulted from the “indirect” invocation of the toString method over the result variable). Now, that really proves that && didn’t really returned a boolean. What’s going on here???

It’s really simple: when you use the && operator to “join” two conditions (expression 1 && expressions 2), the result of that expression will be expression 1 if that expression can be converted to false; if that doesn’t happen, then expression 2 is returned from that evaluation. Operator || has a similar behavior: if expression 1 can be converted into true, it returns that expression; otherwise, it returns the other expression.

If you’ve done some JS in the past, have moved on to other areas and have just returned to it now, you might be a little confused. And that’s ok because things didn’t always worked out like this in the past. If I’m not mistaken, in JS 1.1 the evaluation of an expression which used the && operator or the || operator resulted in a *boolean* value.  The evaluation used at that time was similar to the one described in the previous paragraph. The main difference was that a boolean was returned (instead of the expression that was converted into a boolean).

Before ending, there’s still time to talk about short-circuit evaluation. Since expressions are evaluated from left to right, false && something is always false. On the other hand, true || something is always true. And that’s it for today.  Stay tuned for more.

[Crossposted from http://msmvps.com/blogs/luisabreu]
por Luis Abreu | with no comments
Filed under:
Normalizing a boolean consider WTF
15-9-2009 15:58

In one of my latests posts on JavaScript, I’ve tried to present a technique known as boolean normalization. The idea is to use the ! operator twice in order to convert any value to a boolean. At the time, instead of relying in a simple expression (ex.: var t = !! something), I’ve opted for writing the following function:

function doSomething(isTrue) {
    if (!!isTrue) {
        //some code here
    }
}

I probably wasn’t clear enough about this snippet: I’ve only written it for *illustrative* purposes. Yes, the !! operator isn’t really needed there because we can simply rely on the “interpretation” of truthy and falsy values in JavaScript. On the other hand, it’s also true that using the !! isn’t really causing any harm (in my opinion, it’s only pointless in this simple case).

It happens that the post was interpreted by some as a recommendation, ie, as a good usage of the !! pattern. Some thought the code was so bad, that it deserved its own entry on the Daily WTF.

I must confess that when I’ve written that snippet I wasn’t expecting so much fuss around it. After all, it was only intended to illustrate one way to convert any expression to a boolean. Since I don’t want anyone who reads this blog and is starting with JS to think that there really isn’t any “real” world usage for this pattern, I’ve decided to write a follow up on this topic.

The first thing you need to understand (if you still haven’t, that is) is that using the !! pattern will always yield a boolean, ie, you’ll always get true or false (instead of the original expression). There are some scenarios where you really need a boolean and not an expression.  For instance, the next example shows a function which converts any expression into a boolean (btw, I really don’t have lots of time for writing samples, so I’m assuming that people will not nominate the snippet for WTF based on my the names of the functions :) ):

function isTheParameterValid(par) {
    return !!par;
}

Notice that isTheParameterValid will always convert par into a boolean (it will check for falsy values during the first ! operator execution and the second will convert it back to its “initial boolean value”). If you look at modern JS language libraries, you’ll see that this technique is used whenever the use of a “true” boolean is required. You should keep in mind that both ifs in the next snippet produce the same result:

var t = "something";
if( t ){...
if( isTheParameterValid(t) ){ ...

The difference is that the first is relying on JS evaluation of expressions (based on JS definition of falsy values) and the second is using a "real” boolean. This might be an important difference when you have several conditions, but I’ll leave that for a future post.

I couldn’t really end up this post without looking at the code of some of the existing JS libraries and searching explicitly for the !! usage. And yes, most of its usage falls in one of the scenarios I’ve mentioned before (it will be used for setting a variable to true or false, to return a boolean from a function and when you use the logical &&/|| operators). The surprise was that even JQuery has code which is similar to the one I presented in the previous snippet, ie, it has a simple if with one condition and it uses the !! pattern. Here’s the “guilty" line:

if ( !!document.getElementById( id ) ) {
  Expr.find.ID = function(match, context, isXML){

Interesting, wouldn’t you say? JQuery has a WTF if on it (a least, according to these guys)…

I hope this post makes things perfectly clear regarding the !! pattern. Stay tuned for more on JavaScript.

[Crossposted from http://msmvps.com/blogs/luisabreu]
por Luis Abreu | with no comments
Filed under:
Mais Entradas Página seguinte »