简体   繁体   English

有人可以解释一下此JavaScript / Angular代码如何工作吗?

[英]Can someone explain how this JavaScript/Angular code works?

I'm reading through John Papa's angular style guide and came across this code under the Exception Handling section. 我正在阅读John Papa的有角度的样式指南,并在“ 异常处理”部分下找到了此代码。 Can someone please explain to me where reason comes from or how it works in that code? 有人可以告诉我reason来自何处或在代码中它是如何工作的吗? This is one of those JavaScript/Angular things I just don't get how it works. 这只是我不了解其工作原理的JavaScript / Angular之一。

/* recommended */
angular
    .module('blocks.exception')
    .factory('exception', exception);

exception.$inject = ['logger'];

function exception(logger) {
    var service = {
        catcher: catcher
    };
    return service;

    function catcher(message) {
        return function(reason) {
            logger.error(message, reason);
        };
    }
}

The catcher function returns a function itself that has the argument reason . catcher函数返回一个具有参数reason的函数本身。 In the code you posted, the function isn't called, therefore there is no reason provided, yet. 在您发布的代码中,未调用该函数,因此尚未提供任何reason

Assuming someone has injected exception somewhere else, you could call it like this: 假设有人在其他地方注入了异常,则可以这样称呼它:

var catcher = exception.catcher('This is a message');
var loggerError = catcher('This is the reason');

Or in a single line: 或一行:

var loggerError = exception.catcher('This is a message')('This is the reason');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM