0

I'm writing a javascript file where the variable with revealing pattern is destroyed in the end.

var variable = function () {
  var data = 3;

  function getme () {
    return data;
  }

  return {
    fdata: data,
    me: getme
  };
}();

As there is no in-built delete option for variables, is it ok to replace it with property like this.

this.variable = function () {
  var data = 3;

  function getme() {
    return data;
  }

  return {
    fdata: data,
    me: getme
  };
}();

Because, properties are deletable with delete property_name. Will this break the programming pattern and is it a valid way of coding??.

Ben Thomas
  • 3,180
  • 2
  • 20
  • 38

3 Answers3

0

Say you have a global variable foo and you want to delete it. You can't just delete since it only works for properties.

What you can do is explicitly declare a global variable:

window.foo = 'bar'; // this == window (if not in any function)

Then you can delete:

delete window.foo;

Now if you try to access it you will get:

console.log(foo) // ReferenceError
console.log(window.foo) // undefined

You can't just define with var foo otherwise the deletion won't work.

Anyway if I were you I won't bother "deleting" variables since the garbage collector will handle that.

Fahmi
  • 2,607
  • 1
  • 20
  • 15
0

http://webcache.googleusercontent.com/search?q=cache:auElwuFsub0J:perfectionkills.com/understanding-delete/+delete+javascript&cd=2&hl=en&ct=clnk

Difference between variable declaration syntaxes in Javascript (including global variables)?

Thanks to these posts, i feel a lot clear now. var x and this.x both create properties of global objects only difference being former sets x's 'DontDelete' attribute to false whereas latter sets it to true.

For much internal details, former keeps track of that variable in 'Declarative environment record' and the latter does the same in 'Object environment record' (What really is a declarative environment record and how does it differ from an activation object?)

-1

Both code are same.

Indeed when you create a var in JS, this is attached to the window object (or this if you are out of any function).

var test = 1;
alert(test);
this.test = 2
alert(test);
window.test = 3;
alert(test);
Kashkain
  • 513
  • 4
  • 11