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:
My goal is to use it like this:
const arr = [{}, {}, {}, {}];
arr.last === arr[arr.length - 1];
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With