getter可以根据类型调用电话(firt。属性或函数)返回thunk或值吗?

发布于 2025-01-24 07:50:47 字数 646 浏览 3 评论 0原文

我知道这是一个奇怪的问题,但无论如何我都会问。

下面的伪代码功能提供了虚拟属性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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眉黛浅 2025-01-31 07:50:47

不,无法从多重中了解其使用时返回的值是否将用作函数或用作非功能。

您始终可以返回一个函数,并在该功能上提供直接值作为属性,但是在一个情况下不能返回一个数字,而是在另一个情况下返回一个函数。

您还可以在[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/or toString 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, or multiple vs. multipleThunk, etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文