0

I have array and want access by property (not function) like:

let arr = [1,2,3];
console.log("last element: ", arr.last)

I try like it, but got error:

Array.prototype.last = (() => {
    return this[this.length - 1];
})();

Update 1: yes i know how do it like extend method:

 Array.prototype.mysort = function() {
        this.sort(() => Math.random() - 0.5);
        return this;
    }
    myarray.mysort();

but how do it like property?

myarray.mysort;
isherwood
  • 52,576
  • 15
  • 105
  • 143
padavan
  • 389
  • 2
  • 9

1 Answers1

1

You can do this with a getter. You need to use Object.defineProperty() to add a getter to an existing object, in this case the Array.prototype object.

Object.defineProperty(Array.prototype, "last", {
  get: function() {
    return this[this.length - 1];
  }
});

const a = [1, 2, 3];
console.log(a.last);
Barmar
  • 669,327
  • 51
  • 454
  • 560