简体   繁体   English

此JS代码是否正确OOP?

[英]Is this JS code properly OOP?

I'm trying to keep my JS code nice and OOP from now on. 从现在开始,我一直在努力保持JS代码的美观和OOP。 I think I've gotten the hang of it, could you check this code below and let me know if there are any glaring errors? 我想我已经掌握了窍门,您能在下面检查这段代码,让我知道是否有任何明显的错误吗?

/*------- 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();

One question, is there a better way to get the class instance without passing $this down everytime? 一个问题,是否有一种更好的方法来获取类实例而无需每次都传递$ this? I'd love to hook events like this: 我很想钩住这样的事件:

$(document).ready(setEvents);

And in the setEvents function, have this be an instance of the "collapser." 而在setEvents功能,有this是一个实例“崩塌”。 Is there a way to do this? 有没有办法做到这一点?

Thanks in advance! 提前致谢!

Thanks everyone. 感谢大家。

It turned out to be OOP enough for what I wanted (singleton web-apps / widgets). 事实证明,这足以满足我的需求(单个Web应用程序/小部件)。

I've since moved on to AngularJS . 从那以后,我开始学习AngularJS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM