通过从DOM中删除它的代码来清理javascript变量范围 [英] Cleaning javascript variable scope by removing it's code from DOM

查看:88
本文介绍了通过从DOM中删除它的代码来清理javascript变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望这个基于jquery的简单代码将有助于解释问题。

Hope this jquery based simple code will help to explain the issue.

html:

<script> 
  $('#remover').click(function(){
   $('#block').empty();
  })
  $('#test').click(function(){
   alert(remove1);  // still displays the varibale
  })
</script>
<div id="block">  
 <script>
    var remove1 = 'asasdsds';
    var remove2 = 'asasdsds';
    var remove3 = 'assdsdsdas';         
    var blabla = 'blablabl';
 </script>
</div>

<span id="remover">Remove ALL</span>
<span id="test">Test</span>  // it will still displays the variable.

我需要通过删除块内容来清除全局范围内的所有变量。该块内容是动态的,可以包含任何JavaScript代码。

I need to clear all variables from global scope by removing the block content. The block content is dynamic and can contain any javascript code.

感谢阅读。

推荐答案

这当然不会工作正如你所料。 JavaScript堆没有耦合到DOM - 一旦脚本执行,并且突变了堆,你就不能通过删除它们的相关源代码来解除它们。

This certainly won't work as you expect. The JavaScript heap is not coupled to the DOM - once scripts have executed, and mutated the heap, you can't "unexecute" them by removing their associated source code.

全局变量通常设置在窗口对象上,因此如果您知道名称,可以从中删除它们。如果你想撤消块内的任何JavaScript的效果,那么你几乎没有运气。

Global variables are typically set on the window object, so if you know the names, you can remove them from there. If you want to undo the effects of any JavaScript inside the block, you're pretty much out of luck.

这篇关于通过从DOM中删除它的代码来清理javascript变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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