开发者

Why doesn't the instance variable take the new value

开发者 https://www.devze.com 2023-02-04 14:10 出处:网络
Here is a code example: var testObject = { val1:1, testing:function( ) { val1 = 2; alert( va开发者_开发知识库l1 );

Here is a code example:

var testObject =
{
   val1:  1,

   testing:  function( )
   {
      val1 = 2;
      alert( va开发者_开发知识库l1 );
   }
};

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消