简体   繁体   中英

How does global Javascript object save state?

/**************************************************************************
 *
 * Function:    toggleVis
 *
 * Description: Following Function hides and expands the main column.
 *              
 *
***************************************************************************/
// Set the default "show" mode to that specified by W3C DOM
// compliant browsers

  var showMode = 'table-cell';


// However, IE5 at least does not render table cells correctly
// using the style 'table-cell', but does when the style 'block'
// is used, so handle this

  if (document.all) showMode='block';

// This is the function that actually does the manipulation

var States = { };

function toggleVis(col){

    if (!States[col] || States[col].IsOpen == null)
    {
        States[col] = {isOpen : true}; // This assumes the cell is already shown
        //States[col] = {isOpen : false}; // This assumes the cell is already hidden
    } 

    //mode =  States[col].IsOpen ? showMode : 'none';
    mode =  States[col].IsOpen ? 'none' : showMode; //starts from closed, next click need open

    cells = document.getElementsByName(col);
    for(j = 0; j < cells.length; j++) cells[j].style.display = mode;

    States[col].IsOpen = !States[col].IsOpen;
}

This function hides and displayed a column for a html table. When I call this function the object States toggles accordingly, true if expanded, false if hidden or none. After the function is executed once, what saves the last state of States so that it can be used in this function, when called again? Is it because the object States{} is declared as a global?

Yes. You define States in the outermost closure, which means it's actually a property of the window object as well, that is, window.States === States . However, were you to define a function like

function foo(param) {
    var States = param;
}

it would not affect the global States variable, since you are defining it anew as a local for that function. (But you can access the global States variable, too, by using window.States within that function.)

Absolutely correct. States is declared in the global namespace and is available to all javascript functions (that don't hide it with a variable of the same name). It will retain it's value outside of any function that uses it.

javascript中的全局变量处于活动状态,直到刷新或卸载页面为止。

yes, they are (active until refresh); this is my problem; i save all my popups (ie unsaved input-Forms) in a global array, but after refresh, i cant retreive my popups, because the content of my popup-array is empty; is there a region in the browser, where i can store datastructures browser-wide?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM