简体   繁体   中英

Check if a JavaScript object has already been instantiated

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 ?!

关于什么 ?

this.polyfills = this.polyfills || new Application.Polyfills(this.options);

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.

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.

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