Javascript对象文字返回函数作为键不起作用

标签 javascript object-literal

我有一个函数,它接收两个参数,并返回一个对象文字,但键也是函数( toaster.pop ):

    _self.popCategoryResponse = (msg, param) => ({
        'SAME_CATEGORY_NAME': toaster.pop({
            type: 'error',
            title: 'Ops!',
            body: $translate.instant('categorynameexistsin',
                {name: param.name}),
            bodyOutputType: 'trustHtml'
        }),

        'SAME_ROOT_CATEGORY_NAME': toaster.pop({
            type: 'error',
            title: 'Ops!',
            body: $translate.instant('categorynameexistsinroot'),
            bodyOutputType: 'trustHtml'
        }),

        'BLANK_CATEGORY_NAME': toaster.pop({
            type: 'error',
            title: 'Ops!',
            body: $translate.instant('categorynameisblank'),
            bodyOutputType: 'trustHtml'
        }),

        'NEW_CATEGORY_CREATED': toaster.pop({
            type: 'success',
            title: 'Ok!',
            body: $translate.instant('categorycreated',
                {name: param.name}),
            bodyOutputType: 'trustHtml'
        }),

        'CATEGORY_REMOVED': toaster.pop({
            type: 'success',
            title: 'Ok!',
            body: $translate.instant('categoryremoved',
                {name: param.name}),
            bodyOutputType: 'trustHtml'
        })
    })[msg];

我对这种方法有两个问题:

  1. 现在我用 _self.popCategoryResponse('BLANK_CATEGORY_NAME', node) 调用这个函数,但它不仅仅是调用键 'BLANK_CATEGORY_NAME' 的函数,也适用于其他键。

  2. 有时我不使用 param正如您在某些键中看到的参数一样,调用我的函数是否正确,类似于 _self.popCategoryResponse('BLANK_CATEGORY_NAME', null)

最佳答案

这里的误解似乎是您的对象的键指向在访问时评估的函数。不是这种情况。每次调用 popCategoryResponse 时,您都会创建一个对象,其键是 toaster.pop(...) 的评估结果。 p>

如果您想说服自己,这里有一个例子:

const toaster = [1,2,3,4,5]

// you expect to 'pop' once
// when in fact, it 'pop's three times
const fn = key => ({
  a: toaster.pop(),
  b: toaster.pop(),
  c: toaster.pop()
})[key]

fn('a')
console.log(toaster) // -> [1, 2]

fn()
console.log(toaster) // -> []

这是一个解决方案:

const toaster = [1, 2, 3, 4, 5]

// now the keys are functions which you can invoke to pop only once
const fn = key => {
  const value = {
    a: () => toaster.pop(),
    b: () => toaster.pop(),
    c: () => toaster.pop()
  }[key]

  if (typeof value === 'function') {
    value()
  }
}

fn('a')
console.log(toaster) // -> [1, 2, 3, 4]

fn()
console.log(toaster) // -> [1, 2, 3, 4]

尽管如果您有一个函数改变了超出范围的变量(toaster),我建议考虑另一种方法。至少考虑将其传递给 popCategoryResponse 以实现可测试性。

关于Javascript对象文字返回函数作为键不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51251094/

相关文章:

javascript - 原型(prototype)中的漂亮代码,如何忽略空结果选择器上的 'is not a function' 错误

javascript - 如何在node-red中创建类似mqtt-broker helper的东西

javascript - 嵌套文字对象并按小写过滤

javascript 对象字面量,将同一字面量内的对象值组合在一起

javascript - 如何更改转换 :translate css rule according to the screen resolution?

javascript - 如何在 v-html 之间切换并在 vue.js 中以纯文本形式插入?

javascript - 创建一个包含字符串属性的对象文字

javascript - 在 Javascript 回调列表中添加/删除方法

javascript - 你如何解释这个对象字面量?

javascript - 带输入掩码的千位分隔符