首页 > 解决方案 > 将函数分配给变量的值而不是变量名

问题描述

是否有可能将此函数分配给变量名shortcut而不是变量名?

if (this.commands[this.counter].shortcut) {
  const shortcut = this.commands[this.counter].shortcut;

  tinykeys(window, {
    shortcut: (event) => {
      this.followLink('https://twitter.com');
    },
  });
}

例如: 的值shortcut可能是值为“abc”的字符串,我想得到以下结果:

tinykeys(window, {
  'abc': (event) => {
    this.followLink('https://twitter.com');
  },
});

标签: javascriptfunctionkey-bindings

解决方案


您可以使用计算的属性名称。

[shortcut]: (event) => {
   this.followLink('https://twitter.com');
},

推荐阅读