32

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
    };
}
1
  • none of the solutions work if properties to be used are actually defined prototype and prototype code happens to be below this constructor function. Commented Jul 30, 2015 at 2:06

6 Answers 6

45

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. I actually tried calling 'this.init();' before posting, but I was making the call before the function declaration so that is why it would not work. =]
How should I do the same if I define my object simply by var obj = {init: function(){...}}? How should I call it?
@Eugene - What's wrong with: var makeObj = function(x, y) { return { a: x + y }; } It's a function that creates an object and performs whatever one-time initialization you require before returning it. Sometimes called a factory function.
Well parentlly nothing wrong with it, but had a huge object which was already defined with braces and it wasn't working properly. Now eveything is fine. No problem. :)
12

There is even more smooth way to do this:

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

This will both create method and call it.

1 Comment

Only works if you don't need to set properties in the method. Otherwise Daniel Earwicker ^
3

See below for one possible answer, and some corrections to your code.

function myClass(v1, v2) 
{
    // public vars
    this.var1 = v1;

    // private vars
    // use var to actually make this private
    var var2 = v2;

    // pub methods
    this.init = function() {
        // do some stuff        
    };

    // private methods
    // this will be private as though it had been declared with var
    function someMethod() {
        // do some private stuff
    };

    //call init
    this.init();
}

1 Comment

Thanks, that was a typo when converting my real class to a simple example for the question.
3

JavaScript classes introduced in ECMAScript 2015 are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.

- MDN web docs

When using this syntax, because only the constructor() method is run on instantiation you can't auto-instantiate an object. You always have to add user = new MyUser()

var user;

class MyUser {
  constructor(var1, var2) {

    this.var1 = var1;
    this.var2 = var2;

  }

  static staticMethod() {

    // accessed directly with the class name `MyUser`

  }

  instanceMethod() {

    // accessed with object instance
return true
  }

}

user = new MyUser('hey','there')

Comments

1

Just add

this.init();

to your myClass function.

Comments

1

you could do something like this:

class MyClass {
this.v1 = "hello";

init = () => {
// do something
  }

constructor(){
  this.init()
  }

}

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.