Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Javascript Question

Name: Anonymous 2010-12-15 23:16

new programmer here, just got a simple question.
If I have two function, lets say

function one()
{
   var something = 1;
   two();
}
and

function two()
{
   ...
}

will function two be able to use the something variable or is it only limited to inside one?

Name: Anonymous 2010-12-15 23:21

install gentoo

Name: Anonymous 2010-12-15 23:25

>>1
Wouldn't it have been faster to just try it and see?

Name: Anonymous 2010-12-15 23:35

>>2
No

>>3
Yea, though I'd rather hear it from somebody that knows.

    <script language="javascript">
   
        document.write('hier een<br/>');
        one();
   
        function one()
        {
            document.write('hier twee<br/>');
            var something = 1;
            two();   
        }
       
        function two()
        {
            document.write('hier drie<br/>');
            document.write( something );
            document.write('hier vier<br/>');
        }

   
    </script>

I have this setup and it's not making it to the fourth output, so I guess it's safe to assume no, you can't.

Name: Anonymous 2010-12-16 1:40

In almost every language the mustaches define the scope. Anything within { and } can only see things contained within. There are exceptions, but it's a general rule of thumb.

Name: Anonymous 2010-12-16 2:19

>>5
python

Name: Anonymous 2010-12-16 2:27

>>1
What you're describing is called dynamic scoping. Most sane languages don't have it because it's confusing.

Name: Anonymous 2010-12-16 6:43

Why not have both functions in a class and they can modify a class-member private variable

Name: Anonymous 2010-12-16 7:07

how about

       function one()
        {
            var something = 1;
            return something; 
        }
      
        function two()
        {
            document.write( one());
        }

Name: Anonymous 2010-12-16 7:55

I don't know JavaScript that well, but can't you do

function one()
{
   var something = 1;
   two(something);
}


or something like that?

Name: Anonymous 2010-12-16 8:15

>>1

Do what this anon said:
>>8


<script>

var something; <!-- Global variable -->

function one()
{
   something = 4;
   two();
}

function two()
{
   something = 5;
}
</script>

Name: Anonymous 2010-12-16 11:17

Here are one() and two() in a class-like pattern, as suggested by >>8:

<script>
var MyClass = (function() {
  var constructor = function() {
    // Initialize any instance variables you need here
  };
  constructor.prototype = {
    one: function() {
      this.something = 1;
      this.two();
    },
    two: function() {
      document.write("hier drie<br/>");
      document.write(this.something);  // 1
      document.write("hier drie<br/>");
    }
  };
  return constructor;
}());

var myInstance = new MyClass();
myInstance.one();
</script>

Don't change these.
Name: Email:
Entire Thread Thread List