Javascript 函数decorator中return语句的用途是什么

Javascript 函数decorator中return语句的用途是什么,javascript,function,return,decorator,Javascript,Function,Return,Decorator,我正在学习decorators,但有一件事我不明白——在每个例子中,我都会发现函数末尾有一个return语句。返回语句的目的是什么?在我看来,这是不必要的,它甚至不返回任何东西 console.log('Hello, ' + name); } function loggingDecorator(wrapped) { return function() { console.log('Starting'); const wrapper = wrapp

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

没有它,您的装饰程序就不会沿着包装函数的返回值前进。您的
domething
不会返回任何内容,因此不会使用此行为,但如果您尝试包装其他函数,则需要它

函数doSomethingWithReturn(值){
返回值.toUpperCase();
}
函数loggingDecorator(已包装){
返回函数(){
console.log('Starting');
const wrapper=wrapped.apply(这是参数);
console.log('Finished');
返回包装器;
};
}
const wrapped=loggingDecorator(doSomethingWithReturn);
常数测试=包裹(“丽塔”);

控制台日志(测试);/'RITA',但只有由于'return wrapper'语句
没有它,您的装饰程序才不会沿着包装函数的返回值前进。您的
domething
不会返回任何内容,因此不会使用此行为,但如果您尝试包装其他函数,则需要它

函数doSomethingWithReturn(值){
返回值.toUpperCase();
}
函数loggingDecorator(已包装){
返回函数(){
console.log('Starting');
const wrapper=wrapped.apply(这是参数);
console.log('Finished');
返回包装器;
};
}
const wrapped=loggingDecorator(doSomethingWithReturn);
常数测试=包裹(“丽塔”);

控制台日志(测试);/'丽塔,但仅仅是因为“returnwrapper”语句
Ah,你指的是该“包装器”的
return
;当被调用函数返回值时,这非常有用。这允许日志包装器向调用者提供与实际(包装)函数返回的值相同的值。我认为是这样,但在教程和声誉良好的博客中反复看到这一点对我来说很奇怪。啊,你是指该“包装器”的
返回
;当被调用函数返回值时,这非常有用。这允许日志包装器向调用者提供与实际(包装)函数返回的值相同的值。