是否可以从函数返回const语句



所以,如果我想停止为一个简单的可重复的东西编写许多const语句,是否可以创建一个函数或生成器,或者让我在一行中编写每个语句?

示例常数:

const bgColor = theme('mode', {
default: light.backgroundColor,
dark: dark.backgroundColor,
});
const textColor = theme('mode', {
default: light.color,
dark: dark.color,
});
const shadowColor = theme('mode', {
default: light.boxShadowColor,
dark: dark.boxShadowColor,
});

所需语句示例:

themeProperty('bgColor', backgroundColor);
themeProperty('textColor', color);
themeProperty('shadowColor', boxShadowColor);

因此,缩短代码似乎是个问题。

有两件事被缩短了,第一件是重复的const声明,它确实可以通过使用析构函数赋值来消除。

所以,在我们继续前进之前,让我们先做这件事。

const [bgColor, textColor, shadowColor] = [
theme('mode', {
default: light.backgroundColor,
dark: dark.backgroundColor,
}),
theme('mode', {
default: light.color,
dark: dark.color,
}),
theme('mode', {
default: light.boxShadowColor,
dark: dark.boxShadowColor,
})
];

当然,这是一个最小的改进,但它确实消除了三次键入const的情况。


至于传递的对象,我不知道'mode'为什么消失了,但我会把它添加回来。你可以做的是创建一个目标属性到对象的映射,并提供应该为每个对象提取的公共属性。

const propObjMap = new Map([
["default", light],
["dark", dark],
]);

然后创建一个函数,根据映射和特性名称创建一个新对象。

function mToObj(map, prop) {
const res = {};
for (const [key, obj] of map.entries()) {
res[key] = obj[prop];
}
return res;
}

并像这样使用:

const [bgColor, textColor, shadowColor] = [
theme('mode', mToObj(propObjMap, "backgroundColor")),
theme('mode', mToObj(propObjMap, "color")),
theme('mode', mToObj(propObjMap, "boxShadowColor")),
];

然后因为还有一点重复,您可以创建另一个函数来接收属性列表,并返回一个数组进行析构函数。

function themes(...props) {
return props.map(p => theme('mode', mToObj(propObjMap, p)));
}

因此,现在您的const销毁分配将如下所示:

const [bgColor, textColor, shadowColor] = themes(
"backgroundColor", "color", "boxShadowColor"
);

themes函数可以通过接收'mode'的自变量作为参数,以及在存在其他映射的情况下接收propObjMap的自变量来变得更通用。

function themes(m, map, ...props) {
return props.map(p => theme(m, mToObj(map, p)));
}

让通话看起来像这样:

const [bgColor, textColor, shadowColor] = themes(
'mode',
propObjMap,
"backgroundColor", "color", "boxShadowColor"
);

在Javascript中,它是一个特定的变量声明,决定它是否为const,而const功能仅适用于该特定声明的变量,而不适用于其内容。

因此,不能从const函数中返回值。您必须将它分配给一个声明为const的变量。

const color = themeProperty(...);

在这种情况下,color是常量,这不是因为themeProperty()做了什么,而是因为color变量的声明。

如果你当时这样做了:

const color = themeProperty(...);
let color2 = color;

color2不是const

同样,在themeProperty():中做什么也无关紧要

function themeProperty() {
// only this particular color variable is const
const color = 'red';
return color;        // returning it will not make the value const
}
let x = themeProperty();
let y = x;
x = 'blue';     // allowed because x is not const
y = 'green';    // allowed because y is not const

因此,变量本身是const,仅由其声明决定,而不是指定给其他变量的特定值。

变量的const-ness不能传递给函数或从函数返回。最接近的解决方法是传入或返回冻结的对象(因此对象的属性无法更改)。但是,您不能"冻结"传入或返回的单个值。

最新更新