【发布时间】:2012-05-01 06:37:33
【问题描述】:
我有一个关于如何从面向对象的角度处理特定问题的概念性问题(注意:对于那些对此处的命名空间感兴趣的人,我使用的是 Google Closure)。我对 OOP JS 游戏还很陌生,所以任何和所有的见解都是有帮助的!
假设您要创建一个对象,该对象为页面上与类名 .carouselClassName 匹配的每个 DOM 元素启动轮播。
类似的东西
/*
* 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(参见上面的 cmets)。
绝对欢迎任何关于我的方法的额外 cmets :)
【问题讨论】:
-
构造函数应该大写。
标签: javascript oop closures