0

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?

10
  • Not clear what you are asking. What would obj be if it isn't new consFunc();? Commented Nov 20, 2016 at 7:39
  • this is just for example Commented Nov 20, 2016 at 7:40
  • That doesn't explain much. Commented Nov 20, 2016 at 7:41
  • I am not sure how it should be, maybe I should say consFunc.foo(); i dont know Commented Nov 20, 2016 at 7:41
  • What is wrong with using new consFunc();? Commented Nov 20, 2016 at 7:41

3 Answers 3

1

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'
Sign up to request clarification or add additional context in comments.

5 Comments

haven't you noticed he's using prototype to add a method?? Your answer isn't helping much
@HenryDev I don't think he wants a prototype, check the comment in which I asked what he actually needs
yes I'm with you, but have you seen that in the very beginning of his code he's using prototype?
No Alex I was in need of doing it with prototype
I would advise against the usage of prototypes and constructor functions for situations like this. Please provide more context around your need so we can understand it better.
0

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()

Comments

0

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();

Comments

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.