Question about functional OOP style in JavaScript

Posted by valums on Stack Overflow See other posts from Stack Overflow or by valums
Published on 2010-01-04T12:31:02Z Indexed on 2010/04/04 16:53 UTC
Read the original article Hit count: 401

Filed under:
|
|

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:

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about oop