这段JS代码是正确的OOP吗

Is this JS code properly OOP?

本文关键字:OOP JS 代码 这段      更新时间:2023-09-26

从现在起,我正在努力保持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"的实例。有办法做到这一点吗?

提前感谢!

谢谢大家。

事实证明,对于我想要的(单例web应用程序/小部件(来说,它已经足够OOP了。

从那以后,我转到了AngularJS