首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >是否可以在类型记录中创建一个名为“胖箭头”的lambda?

是否可以在类型记录中创建一个名为“胖箭头”的lambda?
EN

Stack Overflow用户
提问于 2014-12-29 19:37:07
回答 1查看 990关注 0票数 3

使用传统的函数语法,可以内联地创建命名函数。

代码语言:javascript
运行
复制
var fn = function myName(arg) {
    // whatever
};
// fn.name === "myName"

可以使用lambda语法在类型记录中指定名称吗?

代码语言:javascript
运行
复制
var fn = (arg) => {
    // whatever
};
// fn.name not set
EN

回答 1

Stack Overflow用户

发布于 2021-04-23 07:55:10

是的,但有点棘手。

箭头函数从分配它的变量中获取名称。它被称为名称是从变量(在您的例子中是fn.name === "fn")推断的。存在一些限制,因为该名称不能作为常规标识符使用,因此不能从函数本身中使用它(用于递归或事件解除绑定)。

如果使用以下代码:

代码语言:javascript
运行
复制
const joeThrows = (thing: string):never => {
  throw new Error(`Joe took ${thing} and throwed it at you.`);
}

const simonThrows = ({
  simonSays: (what: string):never => {
    throw new Error(`Simon said ${what} and throwed you out.`);
  }
})["simonSays"];


try {
  console.log("== joeThrows fat-arrow %s has name '%s' ==", typeof joeThrows, joeThrows.name);
  joeThrows("hammer");
} catch(ex) { console.log(ex.stack); }

try {
  console.log("=== simonThrows fat-arrow %s has name '%s' ==", typeof simonThrows, simonThrows.name);
  simonThrows("I have a name!");
} catch(ex) { console.log(ex.stack); }

然后,您将得到以下输出:

代码语言:javascript
运行
复制
=== joeThrows fat-arrow function has name 'joeThrows' ==
Joe took hammer and throwed it at you.
Error: Joe took hammer and throwed it at you.
    at joeThrows (/code-demo/named.js:2:11)
    at Object.<anonymous> (/code-demo/named.js:11:5)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    ...
=== simonThrows fat-arrow function has name 'simonSays' ==
Error: Simon said I have a name! and throwed you out.
    at simonSays (/code-demo/named.js:6:15)
    at Object.<anonymous> (/code-demo/named.js:18:5)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    ...

我很少使用对象字段赋值和读取表达式的第二种技术。

当您想要创建更多函数时,可以方便地为不同的设置创建具有相同功能的回调功能,并且希望更精确地可视化异常源,而不是只使用泛型名称。例如,要动态创建非常通用的Redux选择器或FeatherJS挂钩,可以通过函数创建者的参数进行自定义:

代码语言:javascript
运行
复制
// Let's suppose we have the types
type HookContext = Record<string, any>;
type ServiceHook = (context: HookContext) => HookContext;

// Then we can define service hook factory function
export const createServiceHook = (purpose: string): ServiceHook => {
    const fn = `serviceHook$${purpose}`;
    return ({
        [fn]: (context: HookContext): HookContext => {
            // Do something here with the context which may throw exception
            return context;
        }
    })[fn];
};

// Later we can create a specific hook function instance that:
// * will have lookoutForSummer.name equal to "serviceHook$summer"
// * will show that name in call-stack in case exception is throw
export const lookoutForSummer = createServiceHook("summer");
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27694914

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档