/    Sign up×
Community /Pin to ProfileBookmark

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.

to post a comment
JavaScript

14 Comments(s)

Copy linkTweet thisAlerts:
@daihuwsAug 30.2012 — I would use this approach, if I were you: you [B]can[/B] 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
[/CODE]


.. which keeps the variable and function in a namespace of their own and thus reduces the chance of collisions occurring...
Copy linkTweet thisAlerts:
@JMRKERAug 30.2012 — Why not just ...
<i>
</i>&lt;script type="text/javascript"&gt;
var myFlag = false;

function setFlag(flag){ myFlag = flag; }

&lt;/script&gt;
&lt;body&gt;
&lt;button onclick="setFlag(true)"&gt;Set flag&lt;/button&gt;
&lt;button onclick="setFlag(false)"&gt;Reset flag&lt;/button&gt;
&lt;br&gt;
&lt;button onclick="alert(myFlag)"&gt;flag Status&lt;/button&gt;
&lt;/body&gt;
Copy linkTweet thisAlerts:
@Logic_AliAug 31.2012 — 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:

var myFlag = { flag : false };

function setFlag( obj, flag )
{
obj.flag = flag;
}

setFlag( myFlag, true );
An encapsulated solution would still be preferable.
Copy linkTweet thisAlerts:
@Logic_AliAug 31.2012 — Why not just ...
[/quote]
Because it creates two global objects.
Copy linkTweet thisAlerts:
@JMRKERAug 31.2012 — Because it creates two global objects.[/QUOTE]

I see one in the post. Where is the second? ?
Copy linkTweet thisAlerts:
@daihuwsAug 31.2012 — The function setFlag and the variable myFlag - i.e. two global objects.
Copy linkTweet thisAlerts:
@JMRKERAug 31.2012 — The function setFlag and the variable myFlag - i.e. two global objects.[/QUOTE]

OK, I can see that.

But why is this then not 2 global variables?
<i>
</i>var myFlag = { flag : false };

function setFlag( obj, flag ) { obj.flag = flag; }

setFlag( myFlag, true );


Just trying to understand the difference. ?
Copy linkTweet thisAlerts:
@daihuwsAug 31.2012 — 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:

[code=html]<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>[/code]


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.
Copy linkTweet thisAlerts:
@Logic_AliAug 31.2012 — &lt;script type="text/javascript"&gt;

function myFlag( state )
{
var cp = this.constructor.prototype;

if( state !== undefined )
cp.flag = !!state;

return cp.flag; <br/>
}

alert( myFlag() ); // not yet set ( undefined )

myFlag( true ); // set the flag

alert( myFlag() ); // no parameter returns last set value

myFlag( false );

alert( myFlag() );

&lt;/script&gt;
Copy linkTweet thisAlerts:
@JMRKERAug 31.2012 — &lt;script type="text/javascript"&gt;

function myFlag( state )
{
var cp = this.constructor.prototype;

if( state !== undefined )
cp.flag = !!state;

return cp.flag; <br/>
}

alert( myFlag() ); // not yet set ( undefined )

myFlag( true ); // set the flag

alert( myFlag() ); // no parameter returns last set value

myFlag( false );

alert( myFlag() );

&lt;/script&gt;
[/QUOTE]


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...
    <i>
    </i>&lt;!doctype html&gt;
    &lt;html&gt;
    &lt;head&gt;
    &lt;title&gt; Boolean prototype &lt;/title&gt;
    &lt;script type="text/javascript"&gt;

    function myFlag( state ) {
    var cp = this.constructor.prototype;
    if( state !== undefined ) cp.flag = !!state;
    return cp.flag; <br/>
    }

    &lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
    &lt;h1&gt; Boolean Prototype &lt;/h1&gt;
    &lt;button onclick="alert(myFlag())"&gt;Current Status&lt;/button&gt;
    &lt;button onclick="myFlag(true)"&gt;Set Status TRUE&lt;/button&gt;
    &lt;button onclick="myFlag(false)"&gt;Set Status FALSE&lt;/button&gt;
    &lt;/body&gt;
    &lt;/html&gt;
    Copy linkTweet thisAlerts:
    @Logic_AliSep 01.2012 — 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...
    [/quote]


    Actually I realised that in its current state it isn't right because [FONT=Courier New]this[/FONT] is pointing at [FONT=Courier New]window[/FONT]. One way to fix it is this:
    &lt;script type="text/javascript"&gt;

    myFlag = ( new function()
    {
    this.f = function( state )
    {
    var cp = this.constructor.prototype;

    if( state !== undefined )
    cp.flag = !!state;

    return cp.flag; <br/>
    }

    } ).f;


    alert( myFlag() ) // undefined

    myFlag( true )

    alert( myFlag() ) // true

    myFlag( false )

    alert( myFlag() ) // false

    &lt;/script&gt;
    Copy linkTweet thisAlerts:
    @JMRKERSep 02.2012 — 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?
    Copy linkTweet thisAlerts:
    @daveyerwinSep 02.2012 — 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?[/QUOTE]


    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 )[/CODE]
    Copy linkTweet thisAlerts:
    @Logic_AliSep 02.2012 —  could you explain how this new element in post #12 works?

    [/quote]


    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.

    <i>
    </i>myFlag = ( function()
    {
    var flag = undefined;

    return function( state )
    {
    if( state !== undefined )
    flag = !!state;

    <i> </i>return flag;
    }

    })();

    alert( myFlag() ) // undefined

    myFlag( true )

    alert( myFlag() ) // true

    myFlag( false )

    alert( myFlag() ) // false

    ×

    Success!

    Help @docco spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 6.17,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @nearjob,
    tipped: article
    amount: 1000 SATS,

    tipper: @meenaratha,
    tipped: article
    amount: 1000 SATS,

    tipper: @meenaratha,
    tipped: article
    amount: 1000 SATS,
    )...