Adding a getter to Array.prototype

I wanted to add getter to Array.prototype to get the last element of the array.

I did it like this:

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

Is this right for memory? My concern was if you instantiated 10,000 objects:

  • I hope I only have 1 function in memory
  • My concern is that I can have 10,000 * 1 = 10,000 functions in memory

My goal is to use it as follows:

const arr = [{}, {}, {}, {}];
arr.last === arr[arr.length - 1];
+4
source share
2 answers

It works the way you want, the prototype of each instance refers to the same object.

JavaScript - ( proto, prototype ) .

: MDN

:

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

const arr = [1,2,3,4];
const arr2 = [5,6,7,8];

console.log(arr.__lookupGetter__("last") === arr2.__lookupGetter__("last")); // => true iff there is only one last()-function
Hide result
+3

Array.prototype.last = function() {
       return this[this.length - 1];
    };
var arr = [1,2,3,4];
console.log(arr.last());
Hide result

Array, .

+1

Source: https://habr.com/ru/post/1681245/


All Articles