0

I've written a JS object that obfuscates email addresses, however I've discovered two slightly different ways of doing so (each with 1 private method and 1 public method):

Object 1:

var email = new function()
{
    function encrypt(code, key)
    {
        <eliminated for brevity>
    };

    this.mailto = function(address, name)
    {
        link = encrypt(<code>, <key>);
        document.write('<a href="mailto:'+ link +'">'+ name +'</a>');
    }
};

Object 2:

var email = function()
{
    function encrypt(code, key)
    {
        <eliminated for brevity>
    };

    return {
        mailto: function(address, name)
        {
            link = encrypt(<code>, <key>);
            document.write('<a href="mailto:'+ link +'">'+ name +'</a>');
        }
    };
}();

Both of these syntaxes work and can be called with:

email.mailto('example', 'Example');

I'm particularly interested in memory usage or extensibility.
It looks to me as if Object 1 would create a new instance every time it's called?

What are the differences?

SteB
  • 1,999
  • 4
  • 32
  • 57
  • 2
    They both terrible for leaking global variables and using document.write... And there is no *practical* difference (there could be, if `this` was used in any of them). – bfavaretto Sep 09 '13 at 14:58
  • possible duplicate of [Is it right to think of a Javascript Function Expression that uses the 'new' keyword as 'static'](http://stackoverflow.com/questions/10406552/is-it-right-to-think-of-a-javascript-function-expression-that-uses-the-new-key) – Bergi Sep 09 '13 at 15:03

1 Answers1

2

It looks to me as if Object 1 would create a new instance every time it's called?

No. You're doing this with the new keyword already (and once only), email is a static object.

What are the differences?

The first email object does inherit from an extra prototype object that is not apparent in the code. Yet, it does e.g. store the initialisation function, making it non-anonymous. You could create another instance of your module by

var email2 = new (email.constructor)();

This is completely superfluous and probably unintentional.

I'm particularly interested in memory usage

The first option does have an additional prototype object and needs to hold the constructor function in memory, while the second one can garbage-collect the IEFE after it was used. Use the second pattern only, avoid the first one.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks, that's very useful. But what's IIFE? – SteB Sep 09 '13 at 15:15
  • 1
    Immediately-invoked function expression, the construct used for the revealing module pattern (just what you have in example #2) – Bergi Sep 09 '13 at 15:16
  • Last question: In the second example, do all public methods go in the return statement (I've seen this before but don't understand it)? – SteB Sep 09 '13 at 15:20
  • 1
    Yes. The object [literal] that you are returning is the one that is assigned to the `email` variable. – Bergi Sep 09 '13 at 15:23