Mohsin
Mohsin

Reputation: 179

How to return object of constructor from inside the constructor

How can I return the object from constructor from inside the constructor?

 function consFunc() {
  
    this.flag = 'someFlag';
    this.pol = 'somePole';        

    }

    consFunc.prototype.foo = function(){      
     console.log(this.flag);
    }

    var obj = new consFunc();
    obj.foo();

This is how usually I make object from constructor. How can I return object from inside the constructor function so I no need to write var obj = new consFunc(); I just simply call obj.foo(); for my need, is it possible?

Upvotes: 0

Views: 80

Answers (3)

petert
petert

Reputation: 1

If you need some sort of singleton:

var obj = (function (){

    var flag = 'someFlag';
    var pol = 'somePole';   

    function foo(){      
        console.log(flag);
    }

    return {
      foo: foo
    };
})();

obj.foo();

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

You could wrap your constructor in another function and return new consFunc(); from that function:

function obj() {
  function consFunc() {
    this.flag = 'someFlag';
    this.pol = 'somePole';
  }
  consFunc.prototype.foo = function () {
    console.log(this.flag);
  }      
  return new consFunc();
}
// now use it
obj().foo()

Upvotes: 0

Alex Moldovan
Alex Moldovan

Reputation: 2366

If you want to have an object with a simple function on it you can simply write

var consObj = {
  flag: 'someFlag',
  pol: 'somePole',       
  foo: function() { console.log( this.flag ); }
}

consObj.foo() // 'someFlag'

Upvotes: 1

Related Questions