当不存在半色并且键本身是用函数调用的字符串时,nodejs如何解释键值对?

问题描述 投票:0回答:1

我正要在 hexo-cli 中扔一些测试代码,并遇到了以下代码行(可以在here找到完整代码和存储库):

const hexo = proxyquire('../../dist/hexo', {
  './console'(ctx) {
    ctx.extend.console.register('help', spy);
  }
});

我在网上阅读过文章,指出可以使用

proxyquiry
( proxyquery ) 代理模块,然后可以传递键值来模仿这些模块中的方法,如下所示:

var calculateDiscounts = proxyquire(‘./somemodule’, {
  ‘*/cartridge/scripts/hooks/cart/calculateHelpers’: {
    removeAllPriceAdjustments: removeAllPriceAdjustmentsStub
  },
  ‘dw/campaign/PromotionMgr’: {
    getPromotion: getPromotionStub,
    getDiscounts: getDiscountsStub,
    applyDiscounts: applyDiscountsStub
  }
});

带有上述片段的原始文章

那么下面这行代码是如何执行的呢?为什么没有抛出错误,因为它看起来根本不像一个有效的对象?

'./console'(ctx) {
   ctx.extend.console.register('help', spy);
}
node.js mocha.js chai sinon hexo
1个回答
1
投票

这与

相同
'./console': function(ctx) {
   ctx.extend.console.register('help', spy);
}

请参阅 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer?retiredLocale=pl#method_definitionshttps://developer.mozilla.org/en-US /docs/Web/JavaScript/Reference/Functions/Method_definitions

在浏览器中运行良好:

const a = {
  './console'(num) {
    return num * 5
  }
}

console.log(a['./console'](2))

© www.soinside.com 2019 - 2024. All rights reserved.