Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript class - Call method when object initialized

I have a class similar to the one below. How do I call my init method when the object is created? I don't want to have to create an instance of my object then call initialize like I do below.

var myObj = new myClass(2, true); myObj.init();  function myClass(v1, v2)  {     // public vars     this.var1 = v1;      // private vars     var2 = v2;      // pub methods     this.init = function() {         // do some stuff             };      // private methods     someMethod = function() {         // do some private stuff     }; } 
like image 370
Ryan Sampson Avatar asked Aug 19 '10 22:08

Ryan Sampson


People also ask

Which method is called automatically when an object is initialized JavaScript?

The constructor method is a special method of a class for creating and initializing an object instance of that class.

Which method of a class is used to initialize the object JavaScript?

Constructor. The constructor method is a special method for creating and initializing an object created with a class .

Which method of the class is called to initialize an object of that class?

Instantiating a Class When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate.


2 Answers

NB. Constructor function names should start with a capital letter to distinguish them from ordinary functions, e.g. MyClass instead of myClass.

Either you can call init from your constructor function:

var myObj = new MyClass(2, true);  function MyClass(v1, v2)  {     // ...      // pub methods     this.init = function() {         // do some stuff             };      // ...      this.init(); // <------------ added this } 

Or more simply you could just copy the body of the init function to the end of the constructor function. No need to actually have an init function at all if it's only called once.

like image 55
Daniel Earwicker Avatar answered Sep 22 '22 15:09

Daniel Earwicker


There is even more smooth way to do this:

this.init = function(){   // method body }(); 

This will both create method and call it.

like image 31
Kunok Avatar answered Sep 22 '22 15:09

Kunok