javascript-decorators icon indicating copy to clipboard operation
javascript-decorators copied to clipboard

Decorators for function declarations?

Open rauschma opened this issue 10 years ago • 3 comments
trafficstars

Decorators would be very useful for function declarations (incl. generator function declarations). I’d either add that feature to the proposal or mention (e.g. in an FAQ section) why it was postponed/dropped. Python’s decorators work for function declarations.

Use case:

/**
 * Returns a function that, when called,
 * returns a generator object that is immediately
 * ready for input via `next()`
 */
function coroutine(generatorFunction) {
    return function (...args) {
        let generatorObject = generatorFunction(...args);
        generatorObject.next();
        return generatorObject;
    };
}

// Ugly: wrapping
const myCoroutine1 = coroutine(function* () {
    console.log(`First input: ${yield}`);
    return 'DONE';
});

// Nice: decorator
@coroutine
function* myCoroutine2() {
    console.log(`First input: ${yield}`);
    return 'DONE';
}

rauschma avatar Aug 03 '15 13:08 rauschma

Previous discussions: #4 and #30.

sebmck avatar Aug 03 '15 13:08 sebmck

Thanks! Suggestion: a brief section in the proposal that explains why function declarations can’t be decorated.

rauschma avatar Aug 03 '15 13:08 rauschma

@rauschma Thanks for raising this again. You're absolutely right, the proposal should address this. Hopefully that will highlight the issue so that smart people can figure out how functions can be decorated. The only argument I have seen against decorating function is related to the hoisting issue. However, there is a proposal for dealing with this in the thread on issue #4. Briefly, that proposal is that even if the function is hoisted, the decorator is applied at the point where it is declared. I would like to hear from the proposers why they think this won't work.

rtm avatar Aug 03 '15 17:08 rtm