Search code examples
javascriptcoffeescriptglobal-variablesundefinedstrict

Using undefined in self-executing anonymous function


I'm trying to implement namespacing using the self-executing anonymous functions in CoffeeScript:

How do I declare a namespace in JavaScript?

http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/

I wanted to also protect 'undefined' from being redefined, since that's what the article recommends.

So in CoffeeScript, I can do something like:

((skillet, $) ->
  skillet.fry ->
    alert('hi');
)( window.skillet = window.skillet || {}, jQuery);

and get close to the format described in the articles:

(function(skillet, $) {
  return skillet.fry(function() {
    return alert('hi');
  });
})(window.skillet = window.skillet || {}, jQuery);

But when I try to add the undefined in...there's a compilation error due to the strict mode:

http://arcturo.github.com/library/coffeescript/07_the_bad_parts.html

"Certain variables such as undefined are no longer writeable"

I was wondering if there's a work around to this? I would like to keep the strict mode on since there's probably benefits to using it that I am not fully aware of. But even Googling for ways to turn it off...I came up with nil.

Thank you for looking!


Solution

  • I wanted to also protect 'undefined' from being redefined

    and

    There's a compilation error due to the strict mode: "Certain variables such as undefined are no longer writeable"

    So what is your problem? There is no need to declare a undefined argument, because CoffeeScript won't let you use this "variable" anyway!

    If you really (need/want to) worry about some third party script assigning a value to undefined, don't use it in your code. You can always use the typeof operator or CoffeeScripts existential operator instead.

    Just don't worry about it. I think no one ever encountered such an error, apart from explicitly malicious attacks.