Question about functional OOP style in JavaScript
- by valums
I prefer to use functional OOP style for my code (similar to the module pattern) because it helps me to avoid the "new" keyword and all problems with the scope of "this" keyword in callbacks.
But I've run into a few minor issues with it. I would like to use the following code to create a class.
namespace.myClass = function(){
var self = {},
somePrivateVar1;
// initialization code that would call
// private or public methods
privateMethod();
self.publicMethod(); // sorry, error here
function privateMethod(){}
self.publicMethod = function(){};
return self;
}
The problem is that I can't call public methods from my initialization code, as these functions are not defined yet. The obvious solution would be to create an init method, and call it before "return self" line. But maybe you know a more elegant solution?
Also, how do you usually handle inheritance with this pattern? I use the following code, butI would like to hear your ideas and suggestions.
namespace.myClass2 = function(){
var self = namespace.parentClass(),
somePrivateVar1;
var superMethod = self.someMethod;
self.someMethod = function(){
// example shows how to overwrite parent methods
superMethod();
};
return self;
}
Edit.
For those who asked what are the reasons for choosing this style of OOP, you can look into following questions:
http://stackoverflow.com/questions/1557386/prototypal-vs-functional-oop-in-javascript
http://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful