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

时间:2018-07-09 17:32:06

标签: javascript object-literal

我有一个函数,该函数接收两个参数并返回一个Object常量,但是键也是函数(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)正确吗?

1 个答案:

答案 0 :(得分:1)

这里的误解似乎是您对象的键指向访问后评估的功能。不是这种情况。每次调用popCategoryResponse时,您正在创建一个对象,其键为求值结果 toaster.pop(...)

如果您想让自己相信这一点,这里是一个示例:

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以获得可测试性。