我已经开始在 JavaScript 中使用这种模式。我不确定我是专门读过它的,还是某天突然想到的。
格式是...
var name = (function() {
var init = function() {
// Init something
$('a').click(show);
};
var show = function() {
// Show something
};
$(init);
})();
这是一个真实世界的例子......
var contactForm = (function() {
var init = function() {
if ( ! $('body').hasClass('contact')) {
return;
};
var form = $('.contact #content form');
form.validate({
rules: {
'full-name': {
required: true
},
'email': {
required: true,
email: true
},
},
messages: {
'email': {
email: 'Please make sure this email is valid.'
}
}
});
};
$(init);
})();
这有什么问题吗?
最佳答案
没有 YUI 实际上将此称为模块模式并在他们的大量代码中使用它。
您甚至可以在匿名函数中执行以下操作。
name = new init();
关于javascript - 我已经开始使用这个 JavaScript 模式。它有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4404800/