簡體   English   中英

將吸氣劑添加到Array.prototype

[英]Adding a getter to Array.prototype

我想將吸氣劑添加到Array.prototype以獲取數組的最后一個元素。

我這樣做是這樣的:

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

這適合記憶嗎? 我擔心的是,如果您實例化10000個對象:

  • 我希望我的內存中只有1個功能
  • 我擔心我的內存中可能有10000 * 1 = 10000個函數

我的目標是像這樣使用它:

const arr = [{}, {}, {}, {}];
arr.last === arr[arr.length - 1];

它以您想要的方式工作,每個實例的原型都引用相同的對象。

在JavaScript中,它們不會被復制-而是在對象實例及其原型之間建立鏈接(其原型屬性,該屬性是從構造函數上的prototype屬性派生的),而屬性和方法是通過沿原型鏈。

閱讀有關使用原型的更多信息: MDN

您可以輕松地對此進行測試:

 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 

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

您可以擴展Array以獲得此信息。

修改基類原型的問題是,如果您這樣做,其他人也可以這樣做,然后合並多個作者的代碼,版本可能會默默沖突。 別人的方法last()的版本可能會在您沒有意識到的情況下覆蓋您的方法,並且可能會在您沒有意識到的情況下返回與您期望的結果不同的結果。

在我看來,更好的方法是提供一種簡單的方法來根據需要圍繞數組創建包裝對象,然后包裝對象具有諸如last()之類的方法,該方法返回其中現在包裝的數組的最后一個元素。 它可能看起來像這樣:

w ([1, 2, 3]).last()

有關包裝方法的更多信息,尤其是應用於數組的last()方法的更多信息,請參見: https : //medium.com/@panuviljamaa/why-javascript-needs-the-method-last-9f4e285f3f7d

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM