Martin Ueding
Martin Ueding

Reputation: 8719

Function gets defined although code block is not executed

I use the following code to use JS Gettext if the language is German.

if (lang == "de") {
    var gt = new Gettext({"domain": "tag_cloud", "locale_data": json_de_data});
    function _(ident) {
        console.debug('gt.gettext("'+ident+'")');
        return gt.gettext(ident);
    }
    console.debug("Using Gettext.");
}
else {
    function _(ident) {
        console.debug('return "'+ident+'"');
        return ident;
    }
    console.debug("Using no translation.");
}

In Firefox, the console shows:

Using Gettext.
gt.gettext("Ubiqitous, but effective.")

In every other browser (Chromiun, Opera, IE, rekonq, Safari), I get this:

Using Gettext.
return "Ubiqitous, but effective."

I tried to remove the else block and that worked in all browsers then, just not for English.

So is the latter _() defined although the else block is not executed? How can I make this work in all browsers?

Upvotes: 2

Views: 142

Answers (1)

xdazz
xdazz

Reputation: 160883

function _(ident) {} function declaration will be evaluated before run-time, which is at the parse-time.

You can change to var _ = function(ident) {}, this way _ will be assigned at run-time.

Get the further reading: Named function expressions demystified

Upvotes: 3

Related Questions