-1

Here is a code example:

var testObject =
{
   val1:  1,

   testing:  function( )
   {
      val1 = 2;
      alert( val1 );
   }
};

how come when alert prints val1, it's says undefined?

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
dave
  • 14,991
  • 26
  • 76
  • 110

1 Answers1

5

No, it doesn't http://jsfiddle.net/qmLMV/

Note that val1: 1 is a property, and the val1 = 2; inside the function body is a variable. Like with all variables, it will undergo identifier resolution. In this case, you are creating an implicit global variable which should be avoided. Declare your variables beforehand.

function() {
    var val1 = 2;
}

Also note this:

var testObject = {
   val1:  1,
   testing: function() {
      var val1 = 2;

      alert(val1); // alerts 2
      alert(this.val1); // alerts 1
   }
};

Use this to access the properties of the object from within that object's method.

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • 1
    @dave, hopefully you'll review the answer in full, as it points out that you are attempting to reference the `val1` property of `testObject` but instead you are referencing an implicit global `val1` variable. This can create all sorts of problems if you try later to access the property directly (it will always be set to `1`), and it may cause conflicts with other scripts if for whatever reason they expect to access an explicit global `val1` variable. – eyelidlessness Jan 11 '11 at 03:09