Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a getter to Array.prototype

Tags:

javascript

I wanted to add a 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 proper for memory? My worry was if you instance 10000 objects:

  • I hope I will only have 1 functions in the memory
  • My worry is that I might have 10000 * 1 = 10000 functions in the memory

My goal is to use it like this:

const arr = [{}, {}, {}, {}];
arr.last === arr[arr.length - 1];
like image 268
ystal Avatar asked Jul 12 '17 07:07

ystal


2 Answers

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

You can extend Array to get this.

like image 30
Durga Avatar answered Sep 26 '22 01:09

Durga


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

In JavaScript, they are not copied over — instead, a link is made between the object instance and its prototype (its proto property, which is derived from the prototype property on the constructor), and the properties and methods are found by walking up the chain of prototypes.

Read more about working with prototype: MDN

You can easily test this:

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
like image 104
Johan Karlsson Avatar answered Sep 26 '22 01:09

Johan Karlsson