getter可以根据类型调用电话(firt。属性或函数)返回thunk或值吗?
我知道这是一个奇怪的问题,但无论如何我都会问。
下面的伪代码功能提供了虚拟属性Getter。它应该做的是:
> const calc = Calculator(3)
> calc.multiple // returns getter result directly
6
> calc.multiple(4) // returns thunk result, thus behaves like a function
12
这是我的伪代码:
function Calculator(num) {
return {
get multiple() {
if (isFunctionCalled()) { // isFunctionCalled is an
// imaginary function check
return (mult = 3) => {
return mult * num;
};
}
// getter called, default calulation
return 2 * num;
},
};
}
I know this a weird question, but I'll ask it anyway.
The pseudo code function below provides a virtual property getter. What it should do is this:
> const calc = Calculator(3)
> calc.multiple // returns getter result directly
6
> calc.multiple(4) // returns thunk result, thus behaves like a function
12
Here's my pseudo code:
function Calculator(num) {
return {
get multiple() {
if (isFunctionCalled()) { // isFunctionCalled is an
// imaginary function check
return (mult = 3) => {
return mult * num;
};
}
// getter called, default calulation
return 2 * num;
},
};
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,无法从
多重
中了解其使用时返回的值是否将用作函数或用作非功能。您始终可以返回一个函数,并在该功能上提供直接值作为属性,但是在一个情况下不能返回一个数字,而是在另一个情况下返回一个函数。
您还可以在
[symend.tprimitive]
,valueof
和/或toString
操作您返回的功能上操作,但是在野外使用时,倾向于产生令人惊讶的结果。您最好按名称区分
多个
vs.getmultiple
或多个
vs.乘以Multiplethunk
等。No, there's no way to know from within
multiple
whether the value it returns, when used, will be used as a function or used as a non-function.You could always return a function and provide the immediate value as a property on that function, but you can't return a number in one case but a function in another.
You can also play games with overriding the
[Symbol.toPrimitive]
,valueOf
, and/ortoString
operations on the function you return, but that tends to produce surprising results when used in the wild.You're probably best off differentiating by name,
multiple
vs.getMultiple
, ormultiple
vs.multipleThunk
, etc.