Reputation: 2160
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.
Upvotes: 1
Views: 156
Reputation: 664630
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.
Upvotes: 1
Reputation: 535
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.
Upvotes: 0