Reputation: 9701
I'm developing a small game and I instantiate a few objects like this :
this.polyfills = new Application.Polyfills(this.options);
The thing is that that piece of code it's called a bunch of times on click ( of some element on the page ) and I would like not to instantiate that object each time as it already did it's purpose. I have tried something like this :
this.polyfills = window.Application.Polyfills || new Application.Polyfills(this.options);
But the above obviously doesn't work :) So what would be the way to go and do what I just described ?
EDIT : The object ( I call it a class ) that is instantiated on click is this one :
Application.Level = function(_level, _levels, callback) {
this.helpers = (this.helpers instanceof Application.Helpers) ? true : new Application.Helpers();
var self = this,
_options = {
levels : {
count : _levels,
settings : (_level === undefined || _level === '') ? null : self.setLevelSettings(_level, _levels),
template : 'templates/levels.php'
},
api : {
getImages : {
service : 'api/get-images.php',
directory : 'assets/img/'
}
}
};
this.options = new Application.Defaults(_options);
this.polyfills = (this.polyfills instanceof Application.Polyfills) ? true : new Application.Polyfills(this.options);
return this.getImages(self.options.api.getImages.service, { url : self.options.api.getImages.directory }, function(data){
return (typeof callback === 'function' && callback !== undefined) ? callback.apply( callback, [ data, self.options, self.helpers ] ) : 'Argument : Invalid [ Function Required ]';
});
};
Which contains a collection on properties defined through the prototype
. So what I'm trying to do might not be possible ?!
Upvotes: 3
Views: 3981
Reputation: 8658
I use something as simple as :
if(typeof myClass.prototype === "undefined") {
// the class is instanciated
}
Please check this pen to see a working example.
I like it because it does not rely on the context of the call.
Upvotes: 0
Reputation: 1275
Use instanceof:
this.polyfills = this.polyfills instanceof Application.Polyfills ? this.polyfills : new Application.Polyfills(this.options)
This will verify that it's not just an object, but that it's an Application.Polyfills instantiation.
Upvotes: 3
Reputation: 669
What about ?
this.polyfills = this.polyfills || new Application.Polyfills(this.options);
Upvotes: 9