I have an literal object which do something, this object must assigns some initial data to variables before use any of its methods.
var slideshow = {
slideshowBox: null,
slideImages: null,
slideImagesLen: 0,
init: function(){
this.slideshowBox = document.getElementById('slideshow');
this.slideImages = document.getElementById('images');
this.slideImagesLen = this.slideImages.children.length;
},
show: function(){
return this.slideImagesLen;
}
};
But the problem when use any of its method you must firstly use init
method then use I can use any of other methods, but this behavior is not good.
slideshow.init()
console.log(slideshow.show());
Also I have tried to use the following way:
(function(){
var slideshow = {
slideshowBox: null,
slideImages: null,
slideImagesLen: 0,
init: function(){
this.slideshowBox = document.getElementById('slideshow');
this.slideImages = document.getElementById('images');
this.slideImagesLen = this.slideImages.children.length;
},
show: function(){
return this.slideImagesLen;
}
};
slideshow.init();
})();
But, there are some errors like this.slideImages is null
, slideshow.show is not a function
I want any way to call init
method automatically before use any method and without need to calls it manually.
you should try to use prototypal inheritance with a constructor here.
I actually would go a bit further to make it more extendable