javascript - 面向对象的 Javascript 和多个 DOM 元素

标签 javascript oop closures

我有一个概念性问题,关于如何从面向对象的 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,我做了一些观察:

  1. 在我的构造函数对象 (this.classname) 中定义的属性可通过其他原型(prototype)对象中的 this 操作来使用。
  2. 使用 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/

相关文章:

javascript - moment.utc 在 IE 和 Safari 中不起作用

java - 创建一个单独的对象并从 Java 中的对象引用编辑它

javascript - HTML5 - Web SQL 数据库文件存储和所有表的创建位置

javascript - jQuery 创建新数组并将旧数组加倍

ios - 面向对象 - 父类(super class)中的 iOS isEqual 方法,它对子类是否正常工作?

oop - 什么时候使用预定义的类范围访问类型与匿名访问类范围类型作为参数?

Swift 闭包 "Type ' Int ?' is not optional, value can never be nil"

php - PHP 匿名函数中静态变量的作用域

javascript - 如何在 JavaScript 匿名函数的声明时使用变量的值?

javascript - 使用 document.cookie 删除不适用于 firefox 的 cookie