Scope Help: Variables etc

Discussion in 'JavaScript' started by traedrou, Jun 19, 2008.

  1. #1
    Hi guys,

    Just a simple and pretty stupid question...
    Is there a way to get this to work?
    function dbug(e) {
    	e = e.split(',');
    	console.log(this);
    	var ret = '';
    	for(var i=0;i<e.length;i++){
    		ret = ret + e[i] + ': ' + eval(e[i]) + ', ';
    	}
    	console.log(ret);
    }
    PHP:
    Just want to make it easier for me to console.log, so using this I would do
    
    function test() {
    	var variable1 = 'too stupid';
    	var variable2 = 'to properly comprehend';
    	var variable3 = 'how scope works';
    	dbug('variable1,variable2,variable3');
    }
    
    PHP:
    and dbug would log to the console variable1: too stupid, variable2: to properly comprehend, variable3: how scope works

    Anyone know? Thanks :)
     
    traedrou, Jun 19, 2008 IP
  2. rohan_shenoy

    rohan_shenoy Active Member

    Messages:
    441
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    60
    #2
    I read your post thrice but I am so sorry I could not make out what you really wanted. But I will drop a line hoping that that is what you were looking for.

    the keyword var is used to denote local variables, i.e variable which will exist within the function itself.
    Eg
    
    function sayHi()
    {
    var greetings=Hi dear, how are you? Hopes alls fine!
    document.write(greetings);
    //the variable greetings has an assigned value only in the function sayHi()
    if there was no var keyword before that, you could call that varaiable even outside the function
    }
    
    Code (markup):
     
    rohan_shenoy, Jun 19, 2008 IP
  3. koolman

    koolman Peon

    Messages:
    76
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Please try to remove var in the test() function... that will make variable1,variable2,variable3 become global variables.
    Otherwise thoses variables is only inside test() scope

    function test() {
    variable1 = 'too stupid';
    variable2 = 'to properly comprehend';
    variable3 = 'how scope works';
    dbug('variable1,variable2,variable3');
    }
     
    koolman, Jun 20, 2008 IP
  4. MMJ

    MMJ Guest

    Messages:
    460
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
    #4
    function dbug() {
        console.log(this);
    	var args = arguments, i = 0, l = args.length;
        for( ; i < l; i++)
    		console.log(args[i]);
    }
    function test() {
        var variable1 = 'too stupid'
    		,variable2 = 'to properly comprehend'
    		,variable3 = 'how scope works';
        dbug(variable1,variable2,variable3);
    }
    PHP:
     
    MMJ, Jun 21, 2008 IP