Giovanni Bruno
Giovanni Bruno

Reputation: 862

Javascript es6 class syntax pattern

I'm working on a node module and i would like to keep using es6 classes syntax for style consistency but i found this pattern that I can't reproduce:

const proto = module.exports = function(options) {
    man.opts = options || {};
    function man(sentence) {
        man.say(sentence);
    }

    man.__proto__ = proto;
    man.age = 29;
    man.say = function(sentence) {
        console.log(sentence);
    };
    return man;
};

The strange thing of this function is that I can call it as a standard constructor and get a man with his methods and props but I can also call man as a function and get the same result as calling his method "say". Basically man('text') produces the same effect of man.say('text'); How can I recreate this pattern using es6 classes syntax?

Upvotes: 0

Views: 151

Answers (1)

Bergi
Bergi

Reputation: 664217

Basically man('text') produces the same effect of man.say('text')

Best don't use that pattern at all.

How can I recreate this pattern using es6 classes syntax?

You can do it similar to extending Function:

export default class {
    constructor(options) {
        const man = sentence => this.say(sentence);
        Object.setPrototypeOf(man, new.target.prototype);

        man.opts = options || {};
        man.age = 29;

        return man;
    }
    say(sentence) {
        console.log(sentence);
    }
}

Upvotes: 1

Related Questions