简体   繁体   English

检查 JavaScript 对象是否已经被实例化

[英]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 .其中包含通过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.这将验证它不仅仅是一个对象,而是一个 Application.Polyfills 实例化。

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.我喜欢它,因为它不依赖于调用的上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM