Namespacing your code in an object
August Lilleaas says:
Namespacing your code in an object
Disclaimer: This is the (and my) first post/question, and it’s more of a suggestion or finished article than a question or problem that people can comment on. Now, on with the show!
You can use a shotgun blast of local functions.
var showCalendar = function(date){
// ...
}
var daysInMonth = function(){
// ...
}
var firstDayOfMonth = function(){
// ...
}
You can also tuck your code in an object. This cleans up things quite a bit.
Calendar = {
show: function(date){
// ...
},
daysInMonth: function(){
// ...
},
firstDayOfMonth: function(){
// ...
}
}
Calendar.show(new Date())
In addition to providing a clean namespace, an object also gives you this, which is very useful. You can use that to refer to variables and set states from inside the object.
Calendar = {
init: function(date, argetDomId){
this.date = new Date()
this.target = document.getElementById(targetDomId || "default")
this.width = 200
this.height = 500
},
render: function(){
// use this.width, this.target etc here
}
setDate: function(newDate){
this.date = newDate
},
firstDayOfMonth: function(){
// ...
}
}
Calendar.init(new Date())
Calendar.init(new Date(2007, 1, 24), "myCalendarTarget")
In this first submission, August presents not just one but two essential patterns that should be used in JavaScript development:
Namespacing: One of the big dont’s in JavaScript development is “don’t pollute the global namespace”. I.e. create as few global variables as you possibly can. The way to achieve this is simple: Create one global object which serves as a namespace for all your other objects. Namespacing is important in most programming languages, but in the unpredictable environment in which JavaScript runs, it becomes essential to keep interference to a minimum, because you simply don’t know what other code might be in use on the same page.
Encapsulation: JavaScript is an object-oriented language, and we should take advantage of that. Objects have internal state, which means you can put everything related into a black box which knows how to deal with its internals. Outside code only interacts with the object through its public interface, thus reducing coupling.
Comments
Log in to comment.