使用“带”和“带”。 javascript中的声明,在一些极端罕见的情况下 [英] The use of "with" statement in javascript, in some extreme rare cases

查看:65
本文介绍了使用“带”和“带”。 javascript中的声明,在一些极端罕见的情况下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先我知道:


建议不要使用with语句,因为它可能是源
令人困惑的错误和兼容性问题。有关详细信息,请参阅下面说明部分中的Ambiguity Con
段落。

Use of the with statement is not recommended, as it may be the source of confusing bugs and compatibility issues. See the "Ambiguity Con" paragraph in the "Description" section below for details.

https://developer.mozilla.org/en-US/docs/Web/JavaScript /参考/声明/与

但是

如果我们采取这样一个简单的函数(这个功能很棒)

If we take a simple function like this (THIS FUNCTION WORKS GREAT)

function loadImage(url,cb){
 with(new Image)
  onload=cb,
  src=url
}

我们注意到没有任何 CONFUSING 可能会破坏函数闭包内的代码。我们使用的唯一两个变量是 onload & SRC 。直到我不创建变量,对象,数组或函数我命名 onload src 应该发生什么不好。

we notice there is nothing CONFUSING that could break the code inside the function closures. the only 2 variables we use are onload & src. Until i don't create variables, objects,arrays or functions that i name onload or src nothing bad should happen.

说,我的问题是:

javascript垃圾收集器应该在执行后直接将 new Image 添加到集合中?

因此对内存的影响小于标准函数:

And so have less impact to the memory vs a standard function:

function loadImage(url,cb){
 var image=new Image;
 image.onload=cb;
 image.src=url;
}

在上面的例子中 var image 保留在函数内部,直到我执行一个新函数。
顺便说一句。代码也会短得多。

In the above case the var image remains inside the function until i execute a new one. btw. also the code would be much shorter.

// preload a image
function loadImage(a,b){with(new Image)onload=b,src=a}

// convert a file to base64
function readFile(a,b){with(new FileReader)onload=b,readAsDataURL(a)}

可以使用的演示

http://jsfiddle.net/5wqm3/4/ / p>

http://jsfiddle.net/5wqm3/4/

推荐答案


首先我知道:不推荐使用with语句,因为它可能是令人困惑的错误和兼容性问题的来源

不,<$ c $的主要问题c> with 语句是它阻止某些静态优化,因为它在运行时引入了新的变量名 。这也是为什么禁止使用ES 5严格模式代码的原因。

No, the main issue with the with statement is that it prevents certain static optimisations as it introduces new variable names at runtime. That's also the reason why it was forbidden in ES 5 strict mode code.


使用with语句对内存的影响对标准函数的影响较小

Using the with statement should have less impact to the memory vs a standard function

否。 它们的表现完全相同。当函数结束时,新图像 / 图像是没有更多的东西。 图像变量将以与相同的方式消失,语句以结束括号结束。

No. They perform exactly the same. When the function ends, the new Image/image is no more in scope of anything. The image variable will be gone in the same way as the with statement ends with a closing brace.


javascript垃圾收集器应该在执行后直接将 new Image 添加到集合中?

实际上,我不认为该对象是垃圾收集的。它是一个DOM元素,有一个活着的加载处理程序等待它,我认为它仍然是从事件循环队列中引用的。但是,我认为这对你的问题并不重要。

Actually, I don't think the object is garbage-collected. It's a DOM element with an alive load handler waiting for it, I would assume it is still referenced from the event loop queue. However, that doesn't really matter for your question I think.

这篇关于使用“带”和“带”。 javascript中的声明,在一些极端罕见的情况下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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