First of all i know that:
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/Reference/Statements/with
BUT
If we take a simple function like this (THIS FUNCTION WORKS GREAT)
function loadImage(url,cb){
with(new Image)
onload=cb,
src=url
}
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.
Said that, my question is:
The javascript garbage collector should add the new Image
to the collection directly after been executed ?
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;
}
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)}
A demo to play with