我有数组,希望通过属性(而不是函数(访问,如:
let arr = [1,2,3];
console.log("last element: ", arr.last)
我试着喜欢它,但出现了错误:
Array.prototype.last = (() => {
return this[this.length - 1];
})();
更新1:是的,我知道它如何像扩展方法:
Array.prototype.mysort = function() {
this.sort(() => Math.random() - 0.5);
return this;
}
myarray.mysort();
但它喜欢房地产吗?
myarray.mysort;
您可以使用getter来完成此操作。您需要使用Object.defineProperty()
向现有对象添加getter,在本例中为Array.prototype
对象。
Object.defineProperty(Array.prototype, "last", {
get: function() {
return this[this.length - 1];
}
});
const a = [1, 2, 3];
console.log(a.last);