我正要在 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);
}
这与
相同'./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_definitions 或 https://developer.mozilla.org/en-US /docs/Web/JavaScript/Reference/Functions/Method_definitions
在浏览器中运行良好:
const a = {
'./console'(num) {
return num * 5
}
}
console.log(a['./console'](2))