我有 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/