Javascript 对象文字 return 作为键的函数不起作用

Javascript object literal return function as key not working

我有一个接收两个参数的函数,returns一个对象文字,但键也是函数(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(...).

如果你想让自己相信这一点,这里有一个例子:

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 以实现可测试性。