这个JS代码是否正确OOP?

时间:2013-05-22 08:38:47

标签: javascript jquery

从现在开始,我正试图保持我的JS代码和OOP。我想我已经掌握了它,你可以查看下面的代码并让我知道是否有任何明显的错误?

/*------- collapser -------*/
function Collapse(){
    var $this = this;
    $(document).ready(function(e){
        $this.setEvents($this, e);
    });
}
Collapse.prototype.setEvents = function($this, e){    
    $('.collapse>div').hide();
    $('.collapse>h1').click(function(e){
        $this.show($this, e);
    });
}
Collapse.prototype.show = function($this, e){
    var element = e.originalEvent.srcElement.parentNode;
    $(element).children("div").slideToggle();
}
var collapse = new Collapse();

有一个问题,是否有更好的方法来获取类实例而不是每次都将$ this传递给它?我喜欢挂钩这样的事件:

$(document).ready(setEvents);

setEvents函数中,让this成为“collapser”的一个实例。有没有办法做到这一点?

提前致谢!

1 个答案:

答案 0 :(得分:0)

谢谢大家。

事实证明,OOP足以满足我的需求(单身网络应用程序/小部件)。

我已经转到AngularJS

相关问题