www.webdeveloper.com
Results 1 to 15 of 15

Thread: Help for seting value of a var

  1. #1
    Join Date
    Aug 2012
    Posts
    3

    Help for seting value of a var

    Please help what is wrong in the simple function as below
    [CODE]
    <script type="text/javascript">
    var myFlag=new Boolean();

    function setFlag(name,flag){
    name="flag";
    }
    </script>
    [CODE]
    After call the function setFlag(myFlag,true) I want var myFlag=true, but it doesnt work.

  2. #2
    Join Date
    May 2012
    Location
    St. Helens, UK
    Posts
    74
    I would use this approach, if I were you: you can manipulate a global variable from within a function, but it's generally considered a very bad idea.

    Instead, best to create an object to contain both variable and object, like so:

    Code:
    myObject = {
    myFlag: new Boolean,
    setFlag: function() {
    this.myFlag = true;
        }
    }
    
    console.info(myObject.myFlag); // {}
    myObject.setFlag();
    console.info(myObject.myFlag); // true
    .. which keeps the variable and function in a namespace of their own and thus reduces the chance of collisions occurring...
    Last edited by daihuws; 08-30-2012 at 02:48 PM.
    Crisialu Web Design
    Daihuws's Blog

    "There is no human problem which could not be solved if people would simply do as I advise."

  3. #3
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,330

    Lightbulb

    Why not just ...
    Code:
    <script type="text/javascript">
    var myFlag = false;
    
    function setFlag(flag){ myFlag = flag; }
    
    </script>
    <body>
    <button onclick="setFlag(true)">Set flag</button>
    <button onclick="setFlag(false)">Reset flag</button>
    <br>
    <button onclick="alert(myFlag)">flag Status</button>
    </body>

  4. #4
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    The reason it doesn't work is you are passing a variable by value, so the function has no reference to the original so cannot change it.

    Objects are passed by reference, so to a function that expects a reference to an object with a .flag property:

    Code:
    var myFlag = { flag : false };
    
    function setFlag( obj, flag )
    {
       obj.flag = flag;
    }
    
    setFlag( myFlag, true );
    An encapsulated solution would still be preferable.
    Where used, return should be executed unconditionally and always as the last statement in the function.

    That's my signature, it's not part of the damn post!

  5. #5
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    Quote Originally Posted by JMRKER View Post
    Why not just ...
    Because it creates two global objects.
    Where used, return should be executed unconditionally and always as the last statement in the function.

    That's my signature, it's not part of the damn post!

  6. #6
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,330

    Question

    Quote Originally Posted by Logic Ali View Post
    Because it creates two global objects.
    I see one in the post. Where is the second?

  7. #7
    Join Date
    May 2012
    Location
    St. Helens, UK
    Posts
    74
    The function setFlag and the variable myFlag - i.e. two global objects.
    Crisialu Web Design
    Daihuws's Blog

    "There is no human problem which could not be solved if people would simply do as I advise."

  8. #8
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,330

    Question

    Quote Originally Posted by daihuws View Post
    The function setFlag and the variable myFlag - i.e. two global objects.
    OK, I can see that.

    But why is this then not 2 global variables?
    Code:
    var myFlag = { flag : false };
    
    function setFlag( obj, flag )  { obj.flag = flag; }
    
    setFlag( myFlag, true );
    Just trying to understand the difference.

  9. #9
    Join Date
    May 2012
    Location
    St. Helens, UK
    Posts
    74
    That is also two global objects, that is true; but I didn't write that code and as such can't really provide a rationale for it. I'm learning JavaScript at the moment - trying to learn it properly, following best practices, etc. - and something that the experts are unanimous on is that using putting things straight into the global namespace is usually a very bad idea indeed. It may be unlikely, but a situation where an imported library clashed with one of your own functions would lead to unpredictable behaviour and would be quite difficult to debug. Hence my wrapping both variable and function in an object.

    At the risk of overcomplicating things, one could take it a step further by use of a closure:

    HTML Code:
    <html>
    <script>
    var Flag = (function() {
        var myFlag = false;
        function setFlag(state) {
            myFlag = state;
        }
        return {
            falseFlag : function() {
                setFlag(false);
            },
            trueFlag: function() {
                setFlag(true);
            },
            value: function() {
                return myFlag;
            }
        }
    })(); // the pair of brackets at the end are very important
    
    
    document.writeln(Flag.value()+'<br />');
    Flag.trueFlag();
    document.writeln(Flag.value()+'<br />');
    Flag.falseFlag();
    document.writeln(Flag.value()+'<br />');
    </script>
    Using the above code, the flag variable within the function can only be accessed using the function, virtually guaranteeing that no accidental code cross-contamination can occur. Although that's probably overkill for this scenario.
    Crisialu Web Design
    Daihuws's Blog

    "There is no human problem which could not be solved if people would simply do as I advise."

  10. #10
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    Code:
    <script type="text/javascript">
    
    function myFlag( state )
    {
      var cp = this.constructor.prototype;
          
      if( state !== undefined )
        cp.flag = !!state; 
      
      return cp.flag;  
    }
    
    alert( myFlag() ); // not yet set ( undefined )
    
    myFlag( true );    // set the flag
    
    alert( myFlag() ); // no parameter returns last set value
    
    myFlag( false );
    
    alert( myFlag() );
    
    </script>
    Where used, return should be executed unconditionally and always as the last statement in the function.

    That's my signature, it's not part of the damn post!

  11. #11
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,330

    Question

    Quote Originally Posted by Logic Ali View Post
    Code:
    <script type="text/javascript">
    
    function myFlag( state )
    {
      var cp = this.constructor.prototype;
          
      if( state !== undefined )
        cp.flag = !!state; 
      
      return cp.flag;  
    }
    
    alert( myFlag() ); // not yet set ( undefined )
    
    myFlag( true );    // set the flag
    
    alert( myFlag() ); // no parameter returns last set value
    
    myFlag( false );
    
    alert( myFlag() );
    
    </script>
    That is pretty neat! If I'm counting correctly, that is only one global variable created by the JS.

    Could you verify my understanding of what is going on...

    1. After the call to the myFlag() function, first a local variable 'cp' is created as a prototype of the myflag() function.
    [Question: Is 'cp' a local variable or is it global because of the .constructor.prototype command?}

    My assumption here is that the 'cp' variable already has been created for this prototype and is available to be checked
    OR it has not been previously created and the cp assignment is undefined

    2. If the argument (true or false) of the myFlag() function does not exist, then an prototype variable (cp.flag) is created as undefined.

    If the argument (true or false) does exist, then cp.flag is initialized to something (true or false) from the argument passed.

    Now the cp.flag has been created, either with a value of undefined or true/false.

    3. The the status of cp.flag is returned from the myFlag() function.

    It is a bit confusing, but is this anywhere close to what is actually being done or have I got it backwards somewhere?



    I modified it just a bit to make sure I could understand how it is used...
    Code:
    <!doctype html>
    <html>
    <head>
    <title> Boolean prototype </title>
    <script type="text/javascript">
    
    function myFlag( state ) {
      var cp = this.constructor.prototype;
      if( state !== undefined ) cp.flag = !!state; 
      return cp.flag;  
    }
    
    </script>
    </head>
    <body>
    <h1> Boolean Prototype </h1>
    <button onclick="alert(myFlag())">Current Status</button>
    <button onclick="myFlag(true)">Set Status TRUE</button>
    <button onclick="myFlag(false)">Set Status FALSE</button>
    </body>
    </html>

  12. #12
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    Quote Originally Posted by JMRKER View Post
    That is pretty neat! If I'm counting correctly, that is only one global variable created by the JS.

    Could you verify my understanding of what is going on...
    Actually I realised that in its current state it isn't right because this is pointing at window. One way to fix it is this:
    Code:
    <script type="text/javascript">
    
    myFlag = ( new function()
    {
      this.f = function( state )
      { 
       var cp = this.constructor.prototype;
          
       if( state !== undefined )
        cp.flag = !!state; 
      
       return cp.flag;        
      }
      
    } ).f;
    
    
    alert( myFlag() ) // undefined
    
    myFlag( true )
    
    alert( myFlag() )  // true
    
    myFlag( false )
    
    alert( myFlag() )  // false
    
    </script>
    Where used, return should be executed unconditionally and always as the last statement in the function.

    That's my signature, it's not part of the damn post!

  13. #13
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,330
    Now that you have really blown my mind, could you explain how this new element in post #12 works?
    Or how it differs from my earlier analysis in post #11?

  14. #14
    Join Date
    Jul 2011
    Posts
    24
    Quote Originally Posted by JMRKER View Post
    Now that you have really blown my mind, could you explain how this new element in post #12 works?
    Or how it differs from my earlier analysis in post #11?
    He's pointing to tgis ...

    Code:
    function myFlag( state ){
      var cp = this.constructor.prototype;
          alert(this===window)
      if( state !== undefined )
        cp.flag = !!state; 
      
      return cp.flag;  
    }
    
    alert( myFlag() ); // not yet set ( undefined )

  15. #15
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    Quote Originally Posted by JMRKER View Post
    could you explain how this new element in post #12 works?
    Well the idea was to create an instance from an anonymous constructor and save a reference to its member function, but even that is unnecessarily complicated when a simple closure can do the same job.

    Code:
    myFlag = ( function()
    {
      var flag = undefined;
      
      return function( state )
      {
        if( state !== undefined )
          flag = !!state;
          
        return flag;  
      }
      
    })();
    
    alert( myFlag() ) // undefined
    
    myFlag( true )
    
    alert( myFlag() )  // true
    
    myFlag( false )
    
    alert( myFlag() )  // false
    Where used, return should be executed unconditionally and always as the last statement in the function.

    That's my signature, it's not part of the damn post!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles