[Disclaimer]
I do not encourage anyone to do prototype modification in anyone's code, specially shared (or meant to play along with other's).
This is bad practice (if not plain evil).
Much like force-pushing (on non-purely-personal repos/branches) in git and such tomfooleries, this is not meant to be done
(SPECIALLY IF YOU FEEL LIKE YOU CAN PULL THIS OFF SAFELY ...)
[Question]
For educational/study/recreational/sheer-curiosity I would like to know if the optional chaining operator
anObject?.aField
is actually delegated to some function that can be found somewhere like let's say
Object.prototype.hereIAmThatsMeImTheChainingOperatorsDelegateFunctionNiceToMeetYou
And that said operator would be accessed/changed/wrapped/altered. (still not for production/professional/shared code but just for laughs and giggles)
Something like :
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;
}
Much like anyone would be able to do something like
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;
}
[What I tried]
I tried to browse the
Object.prototype
to see if anything looked like the golden ticket but nothing did ...