在传递参数时获取工厂函数的名称(怪异)



好的,所以我有一个问题。

简短版本:我想这样做:

const createThing = function( behaviours(intensities) ){
return {
behaviour1: behaviour1(intensity1),
behaviour2: behaviour2(intensity2)
and so on for each behaviour(intensity) passed as an argument
}
}
//so when doing:
const wtf = createThing( cat(loud), dog(whereistheball), bird(dee) );
// wtf should be:
{
cat: cat(loud),
dog: dog(whereistheball),
bird: bird(dee)
}

我尝试过其他类似的东西:

const createThing = function( behaviours(intensities) ){
return {
for(a in arguments){
[a.name]: a; 
}
}
}

在过去的一周里,我尝试了很多不同的方法来做到这一点,但都没有成功。有人能帮我吗?

长期版本:好的,我有一个磁铁行为工厂函数和一个粒子工厂函数,看起来像这个

const magnet = funtion(intensity) {
// returns a magnetic object with that intensity
}
const createParticle = function( location, static or dynamic, behaviours ){
// returns a particle object with the properties and behaviours listed above
}

问题是我无法让行为部分发挥作用。到目前为止,我有一个磁行为工厂,但我也想有一个电学的、引力的、随机的等等。我想让粒子对象获得行为名称作为新的属性键,当这个行为作为参数传递给粒子工厂函数时,它创建的对象作为这个属性值,类似于这样:

const particle1 = createParticle ( location, dynamic, magnet(intensity) )
//should return
{
location,
dynamic,
magnet: magnet(intensity)
}

甚至

const particle2 = createParticle ( location, dynamic, magnet(intensity), eletric(intensity) )
//should return
{
location,
dynamic,
magnet: magnet(intensity),
eletric: eletric(intensity)
}

等等

我尝试使用方法function.name,但这是不可能的,因为当我将行为函数作为参数传递给粒子时,它会计算为对象。我尝试使用回调函数,然后使用function.name,但它什么也没做,因为我仍然需要将行为函数及其参数传递给粒子工厂。

这可能吗???怎样

不,这是不可能的。除非cat/dog/bird/magnet/eletric都返回一个包含相应工厂名称的对象。

特别是:

function createParticle(...args) {
const particle = { kind: 'particle' };
for (const element of args)
particle[element.kind] = element;
return particle;
}

如果您使用的是类/构造函数+原型,那么您当然可以使用隐式.constructor.name,而不是我在上例中选择的.kind属性。

最新更新