javascript - 函数装饰器中的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
解决方案
没有它,您的装饰器将不会沿着包装函数的返回值转发。您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 - 在 javascript 中访问 HTML 这个对象
- android - 在 Android/iOS 应用中播放受域限制的视频
- python - 使用 pywin32 使用 Flask 构建 Windows 服务时出现问题
- unity3d - 有没有办法使用刚体将游戏对象从点 a 移动到 b 和 b 到 a?
- html - 内容安全策略阻止了 Socket.IO
- http - HTTP长轮询客户端
- python - 无法通过 subprocess.Popen 运行 shell 脚本
- c# - 为什么有些供应商将 Unicode 字符映射到另一个字符集(代码页)?
- vue.js - Vue引导表单标签允许重复
- python - 移位的使用