【问题标题】:What is the purpose of return statement in function decorator函数装饰器中的return语句的目的是什么
【发布时间】:2019-08-28 20:18:56
【问题描述】:

我正在学习装饰器,但我不明白一件事 - 在每个示例中,我都发现函数末尾有一个 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

【问题讨论】:

  • 啊,你的意思是那个“包装器”的return;这在被调用函数返回值时很有用。这允许日志包装器为调用者提供与实际(包装的)函数返回的值相同的值。
  • 我是这么认为的,但在有声望的教程和博客中一遍又一遍地看到这一点让我感到很奇怪。

标签: javascript function return decorator


【解决方案1】:

没有它,你的装饰器就不会沿着包装函数的返回值转发。您的 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

【讨论】:

    猜你喜欢
    • 2015-03-04
    • 2012-12-09
    • 1970-01-01
    • 2021-09-17
    • 2021-11-14
    • 2016-09-08
    • 2018-10-24
    • 1970-01-01
    • 2017-10-11
    相关资源
    最近更新 更多