[英]How to set the prototype of a JavaScript object that has already been instantiated?
[英]Check if a JavaScript object has already been instantiated
我正在开发一个小游戏,我实例化了一些这样的对象:
this.polyfills = new Application.Polyfills(this.options);
问题是那段代码在点击(页面上的某个元素)时被调用了很多次,我不想每次都实例化该对象,因为它已经完成了它的目的。 我试过这样的事情:
this.polyfills = window.Application.Polyfills || new Application.Polyfills(this.options);
但上述显然行不通:) 那么如何去做我刚刚描述的事情呢?
编辑:单击时实例化的对象(我称之为类)是这样的:
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 ]';
});
};
其中包含通过prototype
定义的属性集合。 所以我想要做的可能是不可能的?!
关于什么 ?
this.polyfills = this.polyfills || new Application.Polyfills(this.options);
使用实例:
this.polyfills = this.polyfills instanceof Application.Polyfills ? this.polyfills : new Application.Polyfills(this.options)
这将验证它不仅仅是一个对象,而是一个 Application.Polyfills 实例化。
我使用的东西很简单:
if(typeof myClass.prototype === "undefined") {
// the class is instanciated
}
请检查这支笔以查看工作示例。
我喜欢它,因为它不依赖于调用的上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.