json2021
json2021

Reputation: 2317

How can I automatically invoke a method using a constructor

I have a simple javascript prototype object, with a function defined. Is it possible to have the function invoked when constructing the prototype?

Any help would be really appreciated. Thank you in advance!

function Proto(){

function invoke(){
console.log("I am invoked");
}


}

var proto = new Proto()

Upvotes: 0

Views: 82

Answers (1)

Antiga
Antiga

Reputation: 2274

You could make it an IIFE:

function Proto(){
  (function invoke(){
    console.log("I am invoked");
  })();
}

Or you could just call it in the constructor function:

function Proto(){

  function invoke(){
    console.log("I am invoked");
  }

  invoke();
}

var proto = new Proto()

Upvotes: 4

Related Questions