Coding Style: Please Don't Build JavaScript Classes Like This!
I just picked up DHTML Utopia: Modern Web Design Using JavaScript & DOM by Stuart Langridge. Overall this is an excellent, informative book, and one of the only books out there with up-to-date AJAX information. However, I was extremely disappointed at their choice in OOP style.
The author suggests building "Library Objects" like this one:
Here are some of the reasons why I think this is poor practice:
If you're going to use OOP in JavaScript (and you should!) you really need to use the techniques in the seminal JavaScript: The Definitive Guide from O'Reilly. Please use constructors and
The author suggests building "Library Objects" like this one:
var myObj = {
prop: "hello",
method1: function() {
document.write("this is method1");
},
method2: function() {
document.write(myObj.prop + "");
}
}//end myObj
myObj.method1(); //output: this is method1
myObj.method2(); //output: hello
Here are some of the reasons why I think this is poor practice:
- You can't instantiate multiple copies of your object.
- You don't have a constructor function that can be called when the object is created.
- The syntax requires an additional level of nesting.
- It's easy to forget to add a comma between items and create an error.
If you're going to use OOP in JavaScript (and you should!) you really need to use the techniques in the seminal JavaScript: The Definitive Guide from O'Reilly. Please use constructors and
prototype and new. As described in a previous post, the ideal way to create a Class for the Object listed above is:
var myObj = function(){
this.prop = "hello";
}
myObj.prototype.method1 = function(){
document.write("this is method1");
}
myObj.prototype.method2 = function(){
document.write(this.prop);
}
var obj = new myObj();
obj.method1(); //output: this is method1
obj.method2(); //output: hello