I think perhaps it needs to be stresed that in JavaScript you need to define the object's functions (or methods, if you prefer that term) before you call them.
For example, if you want to call this.func1() upon instantiation:
var new_object = new newObj(); // create/instantiate an object
function newObj(){
this.v1 = 10;
this.v2 = 20;
this.func1(); // <-- calling it here causes an error
this.func1 = function(){ ....};
this.func2 = function(){ ....};
this.func3 = function(){ ....};
}
TypeError: this.func1 is not a function
This is a problem I came across years ago when trying to understand how to do OOP in JS. Because in other languages like Java or PHP, you have a constructor function/method usually at the top of your class, and beneath you write in your other functions/methods.
So it would seem logical to write your class thus: 1) define your object's properties, and then 2) list the things you want to do when the object is instantiated, and then 3) list the other class functions/methods.
BUT NO!!
With JavaScript, you must define the object's functions before you call them.
So if you want to call two methods on object creation/instantiation, lets say this.func1() and this.func2(), first define everything in your class and at the end place your method calls:
var new_object = new newObj(); // create/instantiate an object
function newObj(){
this.v1 = 10;
this.v2 = 20;
this.func1 = function(){ ....};
this.func2 = function(){ ....};
this.func3 = function(){ ....};
this.func1(); // <-- it works here!
this.func2(); // <-- it works here!
}
If you wanted to have your code organised with a constructor method placed at the top of other class methods (like previously mentioned, how PHP and Java do it) then you could make a little this._constructor() method and place things there, and call it at the end of your class:
function newObj(){
this.v1 = 10;
this.v2 = 20;
this._constructor = function(){ // do constructor things here
this.func1();
this.func2();
}
this.func1 = function(){ ....};
this.func2 = function(){ ....};
this.func3 = function(){ ....};
this._constructor(); // call just one method here, nice and tidy
}
Some may say it's kinda redundant, but whatever helps to make your workflow faster... :)
Just for the record, if you want to pass some argument when creating/instantiating an object, say you wanted to have the option to set this.v1 then you could do it like this:
function newObj(set_v1){
this.v1 = 10;
this.v2 = 20;
this._constructor = function(set_v1){ // do constructor things here
if ( set_v1 != undefined ){ // you can come up with a better condition here
this.v1 = set_v1;
}
this.func1();
this.func2();
}
this.func1 = function(){ ....};
this.func2 = function(){ ....};
this.func3 = function(){ ....};
this._constructor(set_v1); // call the constructor here and pass the argument
}