Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I add a property calculated by a JavaScript extension with C#?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

but how do it like property?

myarray.mysort;

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading