0

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?

14
  • function cane(sentence) actually is called man!!! Commented Nov 10, 2016 at 21:06
  • 3
    For the sake of maintainability, don't do that unless you have a very good reason to. Commented Nov 10, 2016 at 21:07
  • @GiovanniBruno You can simple edit your questin to fix mistakes Commented Nov 10, 2016 at 21:24
  • man.__proto__ = proto; is a really, really strange line. Why did you do this? Commented Nov 10, 2016 at 21:26
  • 2
    @zerkms It's officially deprecated by that standard. Commented Nov 10, 2016 at 21:42

1 Answer 1

1

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

1 Comment

understood, tnx! I'll try to refactor my branch of Express removing this terrible pattern but if things becomes too hard I will try this way

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.