I have a conceptual question about how one would approach a particular problem from an object oriented perspective (note: for those interested in the namespacing here, I am using Google Closure). I am fairly new to the OOP JS game so any and all insight is helpful!
Imagine you want to create an object that initiates a carousel for each DOM element on the page that matches a classname .carouselClassName
.
Something like this
/*
* Carousel constructor
*
* @param {className}: Class name to match DOM elements against to
* attach event listeners and CSS animations for the carousel.
*/
var carousel = function(className) {
this.className = className;
//get all DOM elements matching className
this.carouselElements = goog.dom.getElementsByClass(this.className);
}
carousel.prototype.animate = function() {
//animation methods here
}
carousel.prototype.startCarousel = function(val, index, array) {
//attach event listeners and delegate to other methods
//note, this doesn't work because this.animate is undefined (why?)
goog.events.listen(val, goog.events.EventType.CLICK, this.animate);
}
//initalize the carousel for each
carousel.prototype.init = function() {
//foreach carousel element found on the page, run startCarousel
//note: this works fine, even calling this.startCarousel which is a method. Why?
goog.dom.array.foreach(this.className, this.startCarousel, carousel);
}
//create a new instance and initialize
var newCarousel = new carousel('carouselClassName');
newCarousel.init();
Just playing around with OOP in JS for the first time, I've made a few observations:
- A property defined in my constructor object (
this.classname
) is available by thethis
operation in other prototype objects. - A method defined in my constructor object or in the prototype is not available using this.methodName (see comments above).
Any additional comments on my approach to this are definitely welcome :)