OOP Functional Style Question in JavaScript

I prefer to use the OOP functional style for my code (similar to the module template) because it helps me avoid the “new” keyword and all the problems in the “this” area of ​​the keyword in callbacks.

But I ran into a few minor issues. 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 cannot call public methods from my initialization code, since these functions are not yet defined. The obvious solution would be to create an init method and call it before the line "return self". But maybe you know a more elegant solution?

, ? , .

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;
}

. , , , :

+5
4

, , - , , , , ( , , , , ), :

namespace.myClass = function(){  
  //declare private vars (and self) first
  var self = {},  
      somePrivateVar1;  

  //then declare private methods
  function privateMethod(){}  

  //then public/privileged methods
  self.publicMethod = function(){};  

  // THEN (and only then) add your 
  // initialization code that would call  
  // private or public methods  
  privateMethod();  
  self.publicMethod(); // no error any more

  //then return the new object
  return self;  
} 

, ?

0

Zet.js , , .

+2

I have several questions, for example, why you want to avoid the operator newand why you want to call functions before they are defined. However, leaving them aside, what about something more than the following:

namespace.myClass = function(){
  var somePrivateVar1;
  var self = {};

  // initialization code that would call
  // private or public methods
  privateMethod();
  publicMethod();

  function privateMethod(){}
  function publicMethod(){}

  self.publicMethod = publicMethod;
  return self;
}
+1
source

This is the solution that I mentioned in the question. Your comments are welcome.

namespace.myClass = function(){
  var self = {},
      somePrivateVar1;

  function init(){
    privateMethod();
    self.publicMethod();
  }

  function privateMethod(){}
  self.publicMethod = function(){};

  init();
  return self;
}
0
source

All Articles