可选链操作符是否存在于某个原型中且可被修改?
免责声明
我不鼓励任何人在代码中修改原型,尤其是在共享代码(或需与他人协作的代码场景)中。这是不良实践(甚至可以说是恶意行为)。就像在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) /* 预期输出日志: > {"wasItNullIsh":false,"itWas":[1,[null]]} > {"wasItNullIsh":false,"itWas":[null]} > {"wasItNullIsh":true ,"itWas":null} 最终返回undefined */ } finally { Object.prototype.chainOp = originalChainOp; }
这和大家修改Array.prototype.map的操作类似:
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) /* 建议你实际运行试试 */ } finally { Array.prototype.map = originalMap; }
我的尝试
我曾查看Object.prototype寻找类似的核心函数,但一无所获……
内容的提问来源于stack exchange,提问作者Ar3s
相关产品推荐
相关产品推荐

