我有一个概念性问题,关于如何从面向对象的 Angular 处理特定问题(注意:对于那些对此处的命名空间感兴趣的人,我正在使用 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
) 中定义的属性可通过其他原型(prototype)对象中的this
操作来使用。 - 使用 this.methodName 无法使用在我的构造函数对象或原型(prototype)中定义的方法(请参阅上面的注释)。
绝对欢迎对我的方法提出任何其他评论:)
最佳答案
我建议您不要让 Carousel
对象代表页面上的所有轮播。每个都应该是 Carousel
的一个新实例。
您遇到的 this
未正确分配的问题可以通过在构造函数中将这些方法“绑定(bind)”到 this
来解决。
例如
function Carousel(node) {
this.node = node;
// "bind" each method that will act as a callback or event handler
this.bind('animate');
this.init();
}
Carousel.prototype = {
// an example of a "bind" function...
bind: function(method) {
var fn = this[method],
self = this;
this[method] = function() {
return fn.apply(self, arguments);
};
return this;
},
init: function() {},
animate: function() {}
};
var nodes = goog.dom.getElementsByClass(this.className),
carousels = [];
// Instantiate each carousel individually
for(var i = 0; i < nodes.length; i++) carousels.push(new Carousel(nodes[i]));
关于javascript - 面向对象的 Javascript 和多个 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10233303/