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.
-
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.Austin Mullins– Austin Mullins2015年03月17日 15:16:05 +00:00Commented Mar 17, 2015 at 15:16
-
Related.Teemu– Teemu2015年03月17日 15:34:39 +00:00Commented Mar 17, 2015 at 15:34
-
1This code is horrible. Where did you find it?Bergi– Bergi2015年03月17日 15:59:14 +00:00Commented Mar 17, 2015 at 15:59
2 Answers 2
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.
Comments
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.