While others who pointed out that this is possible, I just wanted to point out that as a rule, it is bad practice that constructor functions return an object that is not an instance created by new .
Looking at your example:
function Test() { this.foo = function() {} this.bar = function() {} return function() {}(); } var test = new Test();
(I renamed your test function to test because it is a convention for uppercase functions that you expect to call with new )
What JS does when calling new Test() is that it creates a new instance of the {} object and passes it to the Test() function as the context of this . By default, this object is also what is returned by calling new .
So what you do is attach the foo and bar functions to this newly created isntance object.
Then you return perform another function, which then returns from the call new Test() instead of an instance of the object that has foo and bar on it ... this object is simply lost / dumped by garbage.
This “returning another object from the constructor function” is bad practice and leads to confusion. Plus this happens:
function Test() {} var test = new Test(); test instanceof Test;
however, if you return something else:
function Test() { return function() {}; } var test = new Test(); test instanceof Test;
It would be easier to avoid new and just do:
function test() { var newFunc = function() { console.log('default'); return; }; newFunc.foo = function() { console.log('foo'); return; } newFunc.bar = function() { console.log('bar'); return; } return newFunc; } var t = test(); t();
Codingwithspike
source share