1

I stumbled upon this piece of code:

   function isolate(win, fn) {
        var name = '__lord_isolate';
        var iso = win[name];

        if (!iso) {
            var doc = win.document;
            var head = document.head;
            var script = doc.createElement('script');

            script.type = 'text/javascript';
            script.text = 'function ' + name + '(f){new Function("window","("+f+")(window)")(window)}';
            head.insertBefore(script, head.firstChild);
            head.removeChild(script);

            iso = win[name];
        }

        iso ? iso(fn) : new Function("window", "(" + fn + ")(window)")(win);
    }

is this not the same as self invoking function? Are there any benefits to using this?

Thanks.

3
  • I know that some versions of IE had a tendency to leak function names outside of their intended scope, so maybe this avoids that? I'm really not sure. Commented Mar 17, 2015 at 15:16
  • Related. Commented Mar 17, 2015 at 15:34
  • 1
    This code is horrible. Where did you find it? Commented Mar 17, 2015 at 15:59

2 Answers 2

1

is this not the same as self invoking function?

It's not comparable to a immediately-invoked function expression at all. But it still is a bit different from the seemingly equivalent

function isolate(win, fn) {
    fn(win);
}

as it does stringify fn and re-eval it, destroying all closure in the process.

Are there any benefits to using this?

Yes, it allows you to place a function in a different global scope. If you have multiple browsing contexts (e.g. iframes, tabs, etc), each of them will have its own global scope and global objects. By inserting that script with the content

function __lord_isolate(f) {
    new Function("window", "("+f+")(window)")(window);
}

they are creating an iso function that will eval and call the function f in the given win global context.

Of course, this is more a hack than a solution (and doesn't even work everywhere) and not a good practice, but there may be occasions where it is necessary.

Sign up to request clarification or add additional context in comments.

Comments

0

The name of the function is isolate and it is not self-invoking. There are benefits of using self-invoking functions. For example, it's very useful for initialization.

1 Comment

The main idea of the question was why to use this approach at all

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.