オブジェクト指向の観点から特定の問題にどのように取り組むかについて、概念的な質問があります(注:ここでの名前空間に関心がある人のために、私はGoogle Closureを使用しています)。私はOOPJSゲームにかなり慣れていないので、あらゆる洞察が役立ちます!
クラス名と一致するページ上の各DOM要素のカルーセルを開始するオブジェクトを作成するとします.carouselClassName
。
このようなもの
/*
* 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();
JSで初めてOOPをいじってみたところ、いくつかの観察を行いました。
this.classname
私のコンストラクターオブジェクト( )で定義されたプロパティはthis
、他のプロトタイプオブジェクトの操作で利用できます。- コンストラクターオブジェクトまたはプロトタイプで定義されたメソッドは、this.methodNameを使用して使用できません(上記のコメントを参照)。
これに対する私のアプローチに関する追加のコメントは間違いなく大歓迎です:)