1. With Bracket Notation
With bracket notation, you can access the property like so:
'hello world'[c]
This does the same thing as 'hello world'.length
if c
is 'length'
as a string.
var c = 'length';
console.log('hello world'[c]);
The only difference is that the property is a string. Bracket notation is a property accessor.
2. With Object.defineProperty()
Now if you want an alias:
Object.defineProperty(String.prototype, 'c', {
get: function() {
return this.length;
}
});
console.log("hello world".c);
The above uses Object.defineProperty
to define a property for the existing object, String's prototype
object. That way, all instances of a string will have this new property. Per the documentation:
The Object.defineProperty()
method defines a new property directly on an object, or modifies an existing property on an object, and returns the object.
Syntax
Object.defineProperty(obj, prop, descriptor)
Where obj
is the object being modified, prop
is the new or existing property, and descriptor
is the descriptor for the new or existing property.
Thus, the above defines a property for the object String.prototype
, with name c
. Its descriptor is a get function which returns the length of this
. In the example above, this
refers to the string so it returns the length of the string. You can read more about getters here.
This can also be defined for more types by changing to the applicable prototype (obj
), such as using Object.prototype
instead. However, this has potential issues, as trying to return this.length
on an object without a length property will return undefined, as seen here. You can also use Object.defineProperties
to define multiple properties at a time.