How to structure javascript objects without getting 'undefined', is this not a function error?

If I have a javascript class that runs some initialization code, it seems logical to put this code at the top and any methods at the bottom of the class. The problem is that if the initialization code contains a method call, I get "undefined", this is not a function error. I assume that the method is defined after the method call. How do people usually structure javascript classes to avoid this? Did they put all the initialization code at the end of the class? For instance:

var class = function() { this.start(); this.start = function() { alert('foo'); }; }; var object = new class(); 

causes an error, but:

 var class = function() { this.start = function() { alert('foo'); }; this.start(); }; var object = new class(); 

not. what would be considered a good structure for a javascript object like this?

+4
source share
5 answers
 var class = function() { this.start(); }; class.prototype.start = function() { alert('foo'); }; var object = new class(); 

Now you can mess with the start as much as you want in the constructor. but do not use the keyword class, as this is a reserved word.

0
source

Here is what i will do

 // create a "namespace" var com = com || {}; com.domain = com.domain || {}; // add "class" defintion com.domain.MyClass = function(){ var privateFields = {}; var publicFields = {}; privateFields.myFunction = function(){ // do something } publicFields.initialize = function(){ privateFields.myFunction(); } return publicFields; } var myClass = new com.domain.MyClass(); myClass.initialize(); 

of course you can just do initialize(); "private" and run it before return publicFields;

+2
source

I really work a lot with such structures:

 var foo = function() { // Actual construction code... start(); // <-- doesn't make a difference if functions are privateMethod(); // public or private! // --------------------------------- function start() { // ... whatever ... }; function privateMethod() { // ... whatever ... }; // --------------------------------- // Add all public methods to the object (if start() was only used internally // just don't assign it to the object and it private) this.start = start; }; 
0
source

I like http://ejohn.org/blog/simple-javascript-inheritance/ , where I feel a lot more programming OOP.

 var myClass = Class.extend({ init: function () { this.foo(); }, foo: function () { alert("foo"); } }); new myClass(); 
0
source

Consider the start method on the prototype class . This has a memory saving bonus, since all instances of the class can share the same start instead of creating a new start function for each instance.

 var class = function() { this.start(); }; class.prototype.start = function() { alert('foo'); }; var object = new class(); 
0
source

Source: https://habr.com/ru/post/1401085/


All Articles