0

Is there any way that a variable inside a prototype structure can have the same value across all instances? In my case I need to load the Google API, but I want to make sure that the script is only loaded once.

SharedVariable.prototype.createCache = function ( key, requestFunction, callback ) {

    // <-- this.cache should be a variable shared across all instances

    if ( !this.cache[ key ] ) {
        this.cache[ key ] = $.Deferred( function( defer ) {
            requestFunction( defer );
        }).promise();
    }
    return this.cache[ key ].done( callback );
}

http://jsfiddle.net/BrQkP/

createCache has three parameters:

  1. key is basically the src of the script
  2. requestFunction is a function that is only called once per key.
  3. callback is a function that is called multiple times

This function only works if this.cache is a "global" variable, which should have the same values in all instances. Currently it has a different value for each instance, that's why the code is not working properly. Is something like that possible with prototype?

2
  • Are you creating "instances" of "SharedVariables"? Or do you want all "SharedVariables" to "share a property"? Please make the class name unambiguous. Commented Jul 7, 2014 at 12:33
  • @Bergi In my fiddle I'm creating two instances (new SharedVariables). Each instance has a variable called "cache". I want "cache" to have the same value across all instances. Commented Jul 7, 2014 at 12:50

1 Answer 1

3

Make the cache property part of the prototype:

SharedVariable.prototype.cache = {};

Now all instances of SharedVariable reference the same cache object.

Edit based on your JSFiddle

http://jsfiddle.net/BrQkP/1/

You create the cache as an Array in JavaScript, yet you seem to be setting string key values. You are abusing Arrays in JavaScript, as they are supposed to be integer indexed keys starting at zero. Instead, create an empty object using curly braces as I mentioned above.

Updated fiddle: http://jsfiddle.net/BrQkP/2/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.