javascriptfunctionconstructorchallenge-response

JavaScript constructor whose instances are functions


I know this may be a bizarre question with possibly no practical application, but would it be possible to make a JavaScript class that constructs instances that behave as functions? Here's what I mean:

function Factory() {}

// this may not be necessary, but I'll include it for sake of clarification
Factory.prototype = Object.create(Function.prototype);

var method = new Factory();

method(); // Objective: should not throw TypeError

To further clarify the objective:


Solution

  • If I understand correctly. Object constructor need to return his method. Then you can call it like you describe.

    function Factory() {
        return this.method;
    }
    
    Factory.prototype.method = function() {
        console.log('from method');
    };
    
    var method = new Factory();
    
    method();
    

    http://jsfiddle.net/ydcoL3c2/