zaydek zaydek - 1 month ago 4x
Javascript Question

Add an alias for a property in JavaScript

I think this is fairly simple,

Is there a simple way to add a secondary name for a property (I think this one is String specific – I'm not sure), i.e.,

c = length // this line pseudo code

'hello world'.length // returns 11
'hello world'.c // this line is pseudo code, meant to return 11

In the example above, there's an alias created for the property length. Is that possible to do in JavaScript?



You can access the property like so:

'hello world'[c]

This does the same thing as .length if c = 'length' as a string.

c = 'length'
console.log('hello world'[c])

The only difference is that the property is a string. Using the string as a property name, you can access using brackets. Now if you want an alias:

Object.defineProperty(String.prototype, 'c', {
    get: function() {
        return this.length;

console.log("hello world".c);

This will define a get function for the length as string.c and should correctly return 11. This defines a property for Object, with alias 'c'. It then has a get function which returns the length. You can read more here. This can also be defined for more types by changing to the applicable prototype, or using Object.prototype instead. Although, beware, as trying to return this.length on an object without a length property will return undefined, see here.