首页 > 解决方案 > 函数装饰器中的return语句的目的是什么

问题描述

我正在学习装饰器,但我不明白一件事 - 在每个示例中,我都发现函数末尾有一个 return 语句。该 return 声明的目的是什么?从我的角度来看,这是不必要的,它甚至不会返回任何东西。

    console.log('Hello, ' + name);
}

function loggingDecorator(wrapped) {
    return function() {
        console.log('Starting');
        const wrapper = wrapped.apply(this, arguments);
        console.log('Finished');
        return wrapper; // Why do I need this?
    };
}

const wrapped = loggingDecorator(doSomething);
wrapped('Rita');
const test = wrapped('Rita');
console.log(test); // undefined

标签: javascriptfunctionreturndecorator

解决方案


没有它,您的装饰器将不会沿着包装函数的返回值转发。您doSmething不会返回任何内容,因此不会使用此行为,但如果您尝试包装不同的函数,则需要它。

function doSomethingWithReturn(value) {
  return value.toUpperCase();
}

function loggingDecorator(wrapped) {
    return function() {
        console.log('Starting');
        const wrapper = wrapped.apply(this, arguments);
        console.log('Finished');
        return wrapper;
    };
}

const wrapped = loggingDecorator(doSomethingWithReturn);
const test = wrapped('Rita');
console.log(test); // 'RITA', but only because of the `return wrapper` statement


推荐阅读