可以在某些原型中明确找到可选链吗?

问题描述 投票:0回答:1

[免责声明]

我不鼓励任何人对任何人的代码进行原型修改,特别是共享(或旨在与其他人一起使用)。
这是不好的做法(如果不是纯粹的邪恶)
就像 git 中的强制推送(在非纯粹个人的存储库/分支上)和类似的愚蠢行为一样,这并不是要完成的
(特别是如果您感觉像,您可以安全地完成此操作...)

[问题]

出于教育/学习/娱乐/纯粹的好奇心,我想知道是否有可选的链接运算符

anObject?.aField

实际上委托给了某个可以在某个地方找到的函数,比如让我们说

Object.prototype.hereIAmThatsMeImTheChainingOperatorsDelegateFunctionNiceToMeetYou

并且该操作符将被访问/更改/包装/更改。 (仍然不是用于生产/专业/共享代码,只是为了笑声)

类似的东西:

const originalChainOp = Object.prototype.chainOp;
try {
  Object.prototype.chainOp = function wasItNull() {
    const result = originalChainOp.apply(this, arguments);
    console.log({wasItNullIsh:((this??undefined)===undefined), itWas:this});
    return result;
  };
  [1,[null]]?.[1]?.[0]?.(15)
  /* which would log
   > {"wasItNullIsh":false,"itWas":[1,[null]]}
   > {"wasItNullIsh":false,"itWas":[null]}
   > {"wasItNullIsh":true ,"itWas":null}
   then return undefined
  */
} finally {
  Object.prototype.chainOp = originalChainOp;
}

就像任何人都可以做类似的事情

const originalMap = Array.prototype.map;
try {
  Array.prototype.map = function iWillLogForFun() {
    const result = originalMap.apply(this, arguments);
    console.table({
      before: this,
      after: result
    });
    return result;
  };
  [1, 5, 7].map(x => x - 3) /*which in encourage you to try */
} finally {
  Array.prototype.map = originalMap;
}

[我尝试过的]

我尝试浏览

Object.prototype

看看是否有任何东西看起来像金票,但什么也没做......

javascript functional-programming prototype optional-chaining
1个回答
0
投票

我想知道可选链接运算符是否实际上被委托给某些[内置]函数[c]可以被访问/更改/包装/更改?

不,不是。它由引擎直接评估。

© www.soinside.com 2019 - 2024. All rights reserved.