-2
var objectTest=
{
    test1:  function( )
    {
       val1 = 1;
    },

    // hows accessing the 
    test2:  function( )
    {
       alert( val1 );
    }
};

objectTest.test2( );
user113716
  • 318,772
  • 63
  • 451
  • 440
dave
  • 14,991
  • 26
  • 76
  • 110

4 Answers4

4

By not using the prefix var the variable is put in different (global) scope try instead:

test1: function() {
 var val1=1;
},

As @Pekka points out, your example (above) requires the calling of objectTest.test1(); first (to create val1) otherwise you'll get an error. If you want to access the variable from both places, then you should rather be using an object-property (like @patrick dw suggests) which doesn't add to the global scope

objectTest.test1();
objectTest.test2(); //Shows: Alert-1
alert(val1); //Shows: Alert-1
val1=2;
objectTest.test(2); //Shows: Alert-2
Rudu
  • 15,682
  • 4
  • 47
  • 63
1

It can't. Two functions can't run at the same time, so sharing local scope is impossible the way you show. You would have to define val1 as a member of the object.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
0

Depends on what you ultimately want to do. You could make it a public member of the object:

Example: http://jsfiddle.net/wqr6W/

var objectTest=
{
    val1: 'someDefault',
    test1:  function( )
    {
       this.val1 = 1;
    },

    // hows accessing the 
    test2:  function( )
    {
       alert( this.val1 );
    }
};
objectTest.test1( );
objectTest.test2( );

This of course changes your original code. What you actually need to do will depend on your circumstance.

Or this:

Example: http://jsfiddle.net/wqr6W/1/

var objectTest=
{
    val1: 'someDefault',
    test1:  function( )
    {
       this.val1 = 1;
    },

    // hows accessing the 
    test2:  function( )
    {
       this.test1();
       alert( this.val1 );
    }
};
objectTest.test2( );
user113716
  • 318,772
  • 63
  • 451
  • 440
0

Adding another answer in order to more directly answer the question.

If you are actually talking about a local variable to a function, the simple answer is that you can not access it unless you pass a function out of the function that has the variable, which makes reference to the variable.

This is called creating a closure.

Example: http://jsfiddle.net/csd3s/

var objectTest=
{
    test1:  function( )
    {
       var val1 = 1;
       return {getVal:function() {
           return val1;
       }};
    },

    // hows accessing the 
    test2:  function( )
    {
       alert( this.test1().getVal() );
    }
};

objectTest.test2( );

So inside test2 you can call the test1() function, which returns an object that contains a function, which references the local variable.

That (or something similar) is what it takes to reference an otherwise non-accessible local variable in a function.

user113716
  • 318,772
  • 63
  • 451
  • 440