Search code examples
javascriptinstance-variablesobject-literal

Why doesn't the instance variable take the new value


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?


Solution

  • 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.