javascript - 为大型代码库编写适当的可维护可读 jQuery 的行业和社区最佳实践是什么?

标签 javascript jquery oop readability

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

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

最好有具体的例子。或链接到实际生产代码。指向虚构的理想代码的链接也会有所帮助。

谢谢!

最佳答案

这并不特别适用于 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

关于javascript - 为大型代码库编写适当的可维护可读 jQuery 的行业和社区最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/211769/

相关文章:

javascript - 使用带有动画的 jquery 将 css 背景更改为随机背景

javascript - 使用 jquery 计算 textarea 中的链接数

python - 在 Python 中复制对象实例

python - python中的链式调用父初始化器

php - 这个 php 结构是什么意思 : $html->redirect ("URL")?

javascript - 如何更改按钮的 onclick 属性引用的功能?

javascript - Highcharts 中箱形图中标记的条件着色

jquery - jeditable onblur 函数

javascript - 模态关闭点击内容外

javascript - Electron 中的子窗口并不总是显示在顶部