自毁JavaScript功能 - 它是如何工作的? [英] Self destructing Javascript function - How does it work?

查看:242
本文介绍了自毁JavaScript功能 - 它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我发现这段代码,它显然工作(因为它已经生产多年):

So I found this piece of code and it obviously works (as it has been in production for years):

window[someMethod] = function (tmp) {
    callback({prop:"val"}, tmp); 

    // Garbage collect
    window[someMethod] = undefined;
    try { 
        delete window[someMethod]; 
    } 
    catch (e) { }
    if (head) { 
        head.removeChild(script); 
    }   
    // head refers to DOM head elem and script refers to some script file elem
};

好奇地知道,它是如何工作的?

Curious to know, how does it work?


  1. 如何将自身设置为 undefined c>尝试到
    删除本身?

  2. 浏览器是否知道不执行 undefined delete ,直到呼叫完成?

  3. 如果浏览器立即删除它,那么会发生什么?最后一行是否运行?

  4. 最后,你们看到这个泄漏的记忆吗?如果是,如何?

  1. How can it set itself to undefined within its body and try to delete itself?
  2. Does the browser know to not execute the undefined and delete until the call is finished? And how?
  3. If the browser deletes it right away, then what happens after? Does the last line run?
  4. Finally, do you guys see this leaking memory? If yes, how?


推荐答案


  1. >自身设置为undefined,它将自己的引用设置为undefined。如果你认为一个函数是一个代码块在内存中,那个代码块在这种情况下不会被删除,只是引用它。你从来没有在JavaScript中显式删除任何东西,你只需删除它的引用,并将其留给垃圾收集器清理。注意,这可能不是实际的代码,只是堆对象,因为它的引擎如何处理它(解释,编译,执行它在一个算盘,无论如何)

  2. 基于该逻辑,一旦函数执行,就不再需要对它的原始引用,因为它最初只需要将执行转移给它。

  3. 你误解JS评价为每次发言都要求提及。很可能,这种方法已经被Just-In-Time编译,现在正在执行,就像任何其他非JS函数运行一样。

  4. 上面的代码中没有明显的内存泄漏。

  1. It's not setting itself to undefined, it's setting a reference to itself to undefined. If you think of a function as a block of code in memory, that block of code isn't deleted in this case, just the reference to it. You never explicitly delete anything in JavaScript, you simply remove references to it and leave it to the garbage collector to clean up. Note, this might not be the case for actual code, just heap objects, as its up to the engine how to treat it (interpret it, compile it, execute it on an abacus, whatever)
  2. Based on that logic, once the function is executing, the original reference to it is no longer required as it was needed only initially to transfer execution to it.
  3. You're misunderstanding JS evaluation as requiring a reference to it for every statement. In all likelihood, this method has been Just-In-Time compiled and is now executing just like any other non-JS function would run.
  4. There are no apparent memory leaks in the code above.

希望这很有意义。

这篇关于自毁JavaScript功能 - 它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆