5

来自 Ruby 背景,我习惯于使用带有方法等的类来编写我的所有代码。我确实非常了解 javascript,但我对 jQuery 及其最佳实践并不陌生。

显然有一百万种方法可以在 javascript 中模拟类。但是,实际 jQuery 社区在现实世界中真正使用的是什么?

具体的例子将是理想的。或链接到真实的生产代码。虚构的理想代码的链接也会有所帮助。

谢谢!

4

3 回答 3

3

这不适用于 jQuery,但我喜欢在我自己的代码中模拟类的对象文字语法。

http://ajaxian.com/archives/show-love-to-the-object-literal

我倾向于经常使用这样的(简化的)框架:

var Widget = {

    sound:'bleep',

    load:function(){

        // do stuff here that doesn't need to wait until the DOM is ready.

        // Inside an anonymous function (such as the 'click' handler below),
        // 'this' loses its scope and no longer refers to the widget object.
        // To retain a reference to the widget object, assign 'this' to a
        // variable. I use an underscore... some people like 'self':
        var _ = this;

        // when the DOM is ready, run the init "method":
        $(document).ready(function(){
            _.init(); // the underscore now refers to the widget object
        });

    },

    init:function(){

        var _ = this;

        // whenever a <p class="noisy"> element is clicked, call makeNoise()
        $("p.noisy").click(function(){
            _.makeNoise();
        });

    },

    makeNoise:function(){

        alert(this.sound); // alert 'bleep'

    }

};

Widget.load();

编辑:有关使用“this”关键字的更多信息,如上所述:

http://groups.google.com/group/jquery-en/browse_thread/thread/328d07f90467cccc?pli=1

于 2008-10-21T15:22:21.347 回答
2

我将从这里开始寻找灵感:

http://errtheblog.com/posts/73-the-jskinny-on-jquery

于 2008-10-17T15:29:36.357 回答
0

我在当前项目中使用 jQuery 时遇到了同样的问题,我对 jQuery 也有同样的感觉。它就像大的神秘方法链。当它变大时,需要更多时间来理解我之前写的内容。

我发现制作更易于维护的 jQuery 代码的唯一方法是模块模式。也许它会很有用。你也可以看看 Ajaxian jQuery vs. Prototype: OO JavaScript with or without training Wheels文章关于同样的问题。

于 2010-01-26T11:41:42.840 回答