0

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!

Community
  • 1
  • 1
Zhao Li
  • 4,936
  • 8
  • 33
  • 51
  • Generally, I've never had a problem with `undefined` being redefined - any code that does that is simply not good enough to use, and by using strict mode you ensure that your own code is safe from that too. I wouldn't worry about it! – chrisfrancis27 Jul 25 '12 at 22:23

2 Answers2

2

There is no point in wrapping your CoffeeScript code in a self-executing anonymous - that is already done by default by the compiler.

alert "Foo"

compiles into

(function() {
  alert("Foo");
}).call(this);

If you want to make sure that e.g. $ references jQuery, simply add a local variable:

$ = window.jQuery
skilett = window.skilett ? {}
# ... rest of the code ...

There is also no point in trying to protect undefined while using strict mode, since (as the error message states) undefined is not writable then anyway.

When in "regular" mode, you can generate a variable with the value undefined at the top of your code like this (and simply use this instead of "undefined"):

undef = ((u) -> u)()
Niko
  • 26,516
  • 9
  • 93
  • 110
1

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375