Search code examples
javascriptfunction-prototypes

How to make short name to an Array property


I often have typos in typing word "length" and would like to make a short name to this property. For example "len"

I can easily make an Array method:

Array.prototype.len = function(){ return this.length }

but then i should call [1,2,3].len() with brackets...
But how to make a property? (and call it with [1,2,3].len )

I've tried something like this:

Array.prototype.len = (function(arr) {return arr.length})(this)

but this isn't seen in such way

Thanks in advance


Solution

  • Define a getter like this:

    Array.prototype.__defineGetter__("len", function() {
        return this.length;
    });
    
    var arr = [1, 2, 3];
    arr.len // 3
    

    (Please note: as mentioned in the comments above, it's usually a bad idea to modify the prototype of a native object. Also note that browser support for JavaScript getters/setters is probably sketchy.)