Note that there are some explanatory texts on larger screens.

plurals
  1. POClosure for static values in Javascript
    primarykey
    data
    text
    <p>I have a question. We all know the power of closures in Javascript and I want to use this power. Lets say I have a an object named "BRB". WHat I wanted to is whenever user calls the method getBrowser() for the very first time it will find out browser version/name whatever and return it and also store it inside itself as static when getBrowser() called second time it should return the same value without calculation since it is already statically stored somewhere. This can be done in many different ways, we can just store a property in the object and in the first call we can set some values for it and use it later, we can run getBrowser method directly when object is created in the syntax as</p> <pre><code>(function()( ... ))() </code></pre> <p>However, this is not what I want. All I want is getBrowser() method to calculate the value only once and use it all the time, I dont want to store the value inside the object somewhere else and I dont want to run this method right away when object is created, I'm allowed to use only and only this method and all action must take place in this one method. I put here an example, as you see it will always print out "0" but what I want is it prints 0,1,2,3 for each console.log request. I hope I made myself clear. Thanks.</p> <pre><code>( function(window){ if(window.BRB) return; var BRB = function(){} BRB.prototype.getBrowser = function(){ var browser = null; return function(){ if(browser === null){ browser = 0; } return browser++; } } window.BRB = new BRB(); })(window); console.log(BRB.getBrowser()()); console.log(BRB.getBrowser()()); console.log(BRB.getBrowser()()); console.log(BRB.getBrowser()()); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload