Exception
Exception

Reputation: 8379

How to use prototype method inside return block of a Constructor

I have a Constructor like below

 var Example = (function () {
   function Example(opt) {
     this.opt = opt;
     return{
        function(){ console.log(this.check()); } // Here is an Error
     }   
   }
   Example.prototype.check = function () {
     console.infor('123');
   };
   return Example;
 }) ();

 var ex = new Example({ a:1 });

I know that I am doing wrong but unable to figure out the way to do this. I want to use prototype method inside the object return. Please help me on this.

Upvotes: 0

Views: 91

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388326

Look at

function Example(opt) {
    this.opt = opt;
    this.check()
}
Example.prototype.check = function () {
    console.info('123');
};

Upvotes: 1

Joseph
Joseph

Reputation: 119837

If you wanted to run check() when building an instance, why not call it in the constructor?

var Example = (function () {
  function Example(opt) {
    this.opt = opt;
    this.check(); //this gets called when instances are made
  }
  Example.prototype.check = function () {
    console.infor('123');
  };
  return Example;
}) ();

//so `ex` is an instance of the Example Constructor
//and check gets called when you build it
var ex = new Example({ a:1 });

Upvotes: 2

Related Questions