There is no such thing built-in, as there is rarely a need for it (and sometimes even a need against it).0 It is nevertheless possible to roll your own ‘identity’ key:
const self = Symbol('self');
Object.defineProperty(Object.prototype, self, {
enumerable: false,
get() { "use strict"; return this; }
});
This will work on all primitives (other that null and undefined) and most JavaScript objects: that is, other than proxies or those that bypass the usual prototype chain by means of e.g. Object.create(null)
. Any object later in the prototype chain will also be able to disable the functionality, e.g. by doing { [self]: void 0 }
; all these caveats mean that x[self] === x
is by no means a universal law. But this is probably the best you can do.
Modifying Object.prototype
is usually considered a bad idea, but the above manages to avoid most of its badness: adding the property at a symbol key (and making it explicitly non-enumerable as well) prevents it from unexpectedly showing up in iterations and lookups that walk the prototype chain, helping ensure no code should be impacted that does not specifically look for this property.
0 Even if such a feature existed, it would not be a good solution for the asker’s original use case: a ‘cut to 50 characters or take the whole string if shorter’ operation can be expressed as s.description.substring(0, s.description.length > 50 ? 50 : void 0)
(or in fact just s.description.substring(0, 50)
). It wouldn’t be any easier to express even with such a feature: depending on the condition, you still need to invoke the substring method, not just look it up, but not invoke the ‘self’ non-method. And given that you need to append an ellipsis at the end in the former case, you would still have to perform the condition check outside the substring call, making any shorthand rather ineffective. All that said, tricks like described in this answer do find some real use.
a = [1,2,3]; a.myself = a; x = "myself"; a[x] === a
.. (this is true for, and only for, the shown value of x)substr
is deprecated. Don’t use this method. Secondly,s.description.substring(0, 50)
doesn’t need thislength
check. I don’t see how an “identity” would even help here. This is no longer property access, it’s the conditional operator — two completely different operators.