简体   繁体   English

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

[英]Javascript object literal return function as key not working

I have a function that receives two parameters, and returns an Object literal, but the keys are also functions ( toaster.pop ): 我有一个接收两个参数并返回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];

I have two problems with this approach: 这种方法有两个问题:

  1. Now I am calling this function with _self.popCategoryResponse('BLANK_CATEGORY_NAME', node) , but it is not only calling the function for the key 'BLANK_CATEGORY_NAME' , but also for the other keys. 现在,我使用_self.popCategoryResponse('BLANK_CATEGORY_NAME', node)调用此函数,但它不仅为键'BLANK_CATEGORY_NAME'调用该函数,还为其他键调用该函数。

  2. Sometimes I am not using the param parameter as you can see in some keys, so is it correct to call my function somewhat like _self.popCategoryResponse('BLANK_CATEGORY_NAME', null) ? 有时我不使用param参数,正如您在某些键中看到的那样,所以调用我的函数有点像_self.popCategoryResponse('BLANK_CATEGORY_NAME', null)吗?

The misunderstanding here seems to be that your object's keys point to functions that are evaluated upon access. 这里的误解似乎是您对象的键指向在访问时评估的函数 This is not the case. 不是这种情况。 Every time popCategoryResponse is called, you are creating an object whose keys are the result of evaluating toaster.pop(...) . 每次调用popCategoryResponse ,您都在创建一个对象,其键是 toaster.pop(...) 求值的结果

Here is an example if you want to convince yourself of that: 如果您想让自己相信这一点,请参见以下示例:

 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) // -> [] 

Here is a solution: 这是一个解决方案:

 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] 

Although I would suggest considering another approach if you have a function mutating an out of scope variable ( toaster ). 虽然我建议您考虑使用另一种方法,如果您有一个函数将超出范围的变量( toaster )进行突变。 At least consider passing it in to popCategoryResponse for testability. 至少考虑将其传递给popCategoryResponse以实现可测试性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM