Javascript 具有eventhandler重载的对象
目前我正在尝试用javascript编写resourcemanager。它有两种方法,一种是向管理器添加图像资源,另一种是在添加图像后预加载所有图像:Javascript 具有eventhandler重载的对象,javascript,javascript-events,Javascript,Javascript Events,目前我正在尝试用javascript编写resourcemanager。它有两种方法,一种是向管理器添加图像资源,另一种是在添加图像后预加载所有图像: ResourceManager = function(){}; ResourceManager.prototype = function(){ var imageList = new Array(), addImage = function(imageUrl){ imageList.push(imageUrl);
ResourceManager = function(){};
ResourceManager.prototype = function(){
var imageList = new Array(),
addImage = function(imageUrl){
imageList.push(imageUrl);
},
loadImages = function(){
//Do stuff for loading here
onComplete();
},
onComplete = function(){
alert('finished');
};
return {
addImage: addImage,
loadImages: loadImages,
onComplete: onComplete
}
}();
然后我想用它如下
var rsmgr = new ResourceManager();
rsmgr.onComplete = function(){
alert('completed');
};
rsmgr.addImage('image.png');
rsmgr.loadImages();
您可以看到一个工作示例
现在这种过载不起作用了,为什么会发生这种情况?我猜这和原型设计有关,但我似乎不知道如何解决这个问题 我不是原型设计专家,因此无法给出有效的答案,说明它为什么不起作用,但我可以建议使用纯函数方法的替代方法,该方法效果很好:
function ResourceManager() {
this.imageList = new Array();
this.addImage = function(imageUrl) {
this.imageList.push(imageUrl);
};
this.loadImages = function() {
//Do stuff for loading here
this.onComplete();
};
this.onComplete = function() {
alert('finished');
};
};
像上面那样编写会导致原始重写代码工作-。
如果删除rsmgr.onComplete覆盖,您将按预期完成您链接到JSFIDLE主站点,那里没有工作代码。感谢您的通知,我现在已链接到正确的页面。