Getters \ setters for dummies

后端 未结 12 2287
说谎
说谎 2020-11-22 04:55

I\'ve been trying to get my head around getters and setters and its not sinking in. I\'ve read JavaScript Getters and Setters and Defining Getters and Setters and just not g

12条回答
  •  执念已碎
    2020-11-22 05:30

    I was also somewhat confused by the explanation I read, because I was trying to add a property to an existing prototype that I did not write, so replacing the prototype seemed like the wrong approach. So, for posterity, here's how I added a last property to Array:

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

    Ever so slightly nicer than adding a function IMHO.

提交回复
热议问题