Search code examples
javascriptprototype

How to make custom method in JavaScript


I want to have my own method in JavaScript which can be able to access some property of the preceding method/function Eg:

//default
var arr = [1,6,3,5];
alert(arr.length);

This will alert the length of arr. But I want to use my custom method instead of the length method say len Eg:

//custom
prototype.len = ()=>{
   return prototype.length;
}
var arr = [1,6,3,5];
alert(arr.len);

Solution

  • To define a "getter" without using ES6 class syntax you can use Object.defineProperty:

    Object.defineProperty(Array.prototype, 'len', {
        get: function() {
            return this.length;
        }
    });
    

    Use of .defineProperty will (by default) create a non-enumerable property which ensures that your new property doesn't appear inadvertently in the results of a for .. in ... loop.

    The question of whether it's appropriate to add such a property to a built-in class is a matter of some debate. Some languages explicitly encourage it, some don't.