最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to toggle a global Booleans from one single function? - Stack Overflow

programmeradmin3浏览0评论

So far I am trying with:

var myBoolean = false; // global

function toggleBoolean(vr) {
    vr = !vr;
}

alert(myBoolean); // false
toggleBoolean(myBoolean);
alert(myBoolean); // false

But obviously, It failed.

Edit: sorry, I forgot to point out that I want the function to work with many Booleans and not just one

So far I am trying with:

var myBoolean = false; // global

function toggleBoolean(vr) {
    vr = !vr;
}

alert(myBoolean); // false
toggleBoolean(myBoolean);
alert(myBoolean); // false

But obviously, It failed.

Edit: sorry, I forgot to point out that I want the function to work with many Booleans and not just one

Share Improve this question edited Dec 16, 2011 at 1:02 Jan Pöschko 5,5801 gold badge30 silver badges28 bronze badges asked Dec 15, 2011 at 23:55 user1022373user1022373
Add a ment  | 

3 Answers 3

Reset to default 5

Yes, you can toggle a global boolean from a function. You can't do it as in your attempt because JavaScript is strictly call-by-value.

function toggleBoolean() {
  myBoolean = ! myBoolean;
}

Now, if you want to toggle a global by name, you could do this (though it's a little icky):

function toggleBoolean(name) {
  window[ name ] = ! window[ name ];
}

Global variables (in JavaScript on a browser) are properties of the global object, which is known as "window". In other contexts there are ways of associating a name with the global context. You'd call that function, therefore, like this:

toggleBoolean( "myBoolean" );

Note that I pass a string there instead of a reference to the actual global variable.

you are passing the value to the function by value. Instead, to achieve what you want, you can do something like:

var myBoolean=false;// Global

function toggleBoolean(){
    myBoolean = !myBoolean;
} 

You can do

var myState = { state : false };

function toggleBoolean( s )
{
    s.state = ! s.state;
}

alert( myState.state );
toggleBoolean( myState );
alert( myState.state );

primitives are passed by value by default in javascript. You can have a wrapper object and pass the object to the toggle function.

发布评论

评论列表(0)

  1. 暂无评论