As everyone who’s well trained in software engineering would agree, that one of the principle of writing predictable code is to separate and hide something within only the scope that it’s needed. Controlled access to and from the outside world brings predictability and accountability of your code thus better debugging.
In jQuery, you need constantly extending the native features by writing extra plugins and adding new functions:
var newMethods = {
check : function() { ... },
uncheck : function() { ... },
toggleCheck : function() { ... }
};
jQuery.each(newMethods, function(i) {
jQuery.fn[i] = this;
});
Without proper fencing, the variable containing 3 functions newMethods is everything but protected from the global scope (outside world), increaseing the complexity of the code and difficulty in debugging. To solve this problem, you will want to embrace the code in an anonymous function.
(function() {
var newMethods = {
check : function() { ... },
uncheck : function() { ... },
toggleCheck : function() { ... }
};
jQuery.each(newMethods, function(i) {
jQuery.fn[i] = this;
});
})();
You should also read:
- jQuery: Check / uncheck form checkbox and radio
- Regular Expressions for Natural Numbers or Positive Integers (1, 2, 3, …), Negative Integers and Non-negative Integers
- Incisive Software Engineering & Programming Quotes and Sayings
- jQuery: How to check if an element has a particular class
- How to define multiple CSS rules / properties in jQuery?


Facebook
Twitter
Google Plus