gpt4 book ai didi

javascript - 函数装饰器中return语句的作用是什么

转载 作者:行者123 更新时间:2023-12-01 00:41:17 25 4
gpt4 key购买 nike

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

    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

最佳答案

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

关于javascript - 函数装饰器中return语句的作用是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57699528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com