简体   繁体   中英

Preserve variables in a javascript closure function

I am pretty much a novice in javascript programming and i would really need some help/advice.

What i am trying to do: I have a function (or object?!) which looks like this:

var svgInteraction = function (containerId) {
    var svgNamespace = "http://www.w3.org/2000/svg",
        htmlns = "http://www.w3.org/1999/xhtml",
    mathns = "http://www.w3.org/1998/Math/MathML";

    svgInteractions = {};

    svgInteractions[containerId] = "I am " + containerId;
    console.log(svgInteractions);

    return function () {
        console.log(svgInteractions);
    }
};

i initialize a variable like this:

var svg1 = svgInteraction("container_1");
var svg2 = svgInteraction("container_2");

The problem is that, for each initialization of the svgInteraction, the svgInteractions objects reinitialize.

It outputs:

Object { container_1="I am container_1"}
Object { container_2="I am container_2"}

Is there any way to keep old values inside it?

Thank you

Don't set it to an empty object each time ( svgInteractions = {} ) the function is called.

Try this...

var svgInteraction = (function() {

   var svgInteractions = {};

   return function(containerId) {
     // Implementation
   }

})();

Here, svgInteractions is encapsulated but it will also be static for all calls to svgInteraction .

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