簡體   English   中英

JS原型方法在循環訪問時的行為有所不同

[英]JS Prototype methods act differently while accessing in a loop

我正在使用一種稱為custommethod的新方法擴展數組對象,如下所示,並遍歷數組內部的值。 但是,遍歷索引也將打印通過Array.prototype.<method>擴展的property名稱。

Array.prototype.custommethod = function() {
    console.log("Hello from Custom Method");
}

Object.defineProperty(Array.prototype, "anothercustommethod", {
    value: function() {
        console.log("Hello from Another Custom Method");
    }
});

遍歷數組

> x = [1,2]
[ 1, 2 ]

> for (i in x) { console.log(i); }
0
1
custommethod
  • 為什么在此循環中沒有打印anothercustommethod

  • 使用Object.defineProperty()是創建Array.prototype的更安全方法嗎?

我對javascript中的for循環實際上如何工作感到好奇。 它在內部使用Object.keys()嗎? 如果是這樣,它是如何打印custommethod這里面__proto__財產,但不anothercustommethod這也是內部__proto__屬性?

為什么在此循環中沒有打印出另一個定制方法?

for in迭代這些屬性,將enumerable數據描述符設置為true。

文檔中

枚舉真當且僅當該屬性對應的對象的屬性的枚舉期間顯示出來。 默認為false。

當使用defineProperty ,你也可以通過額外的屬性- 枚舉 默認情況下,它設置為false。

 Array.prototype.custommethod = function() { console.log("Hello from Custom Method"); } Object.defineProperty(Array.prototype, "anothercustommethod", { value: function() { console.log("Hello from Another Custom Method"); }, enumerable: true }); const x = [1,2] for (i in x) { console.log(i); } 

使用Object.defineProperty()是創建Array.prototype的更安全方法嗎?

沒有什么安全的。 嘗試很少更改原型中的構建

您可以通過以下API檢查屬性:

Object.getOwnPropertyDescriptor(Array.prototype,'custommethod');//{value: ƒ, writable: true, enumerable: true, configurable: true}
Object.getOwnPropertyDescriptor(Array.prototype,'anothercustommethod');//{value: ƒ, writable: false, enumerable: false, configurable: false}

看到? 第一個得到:可枚舉:為真,第二個得到:可枚舉:為假,

其他值也不同,這是因為由不同的API設置時默認設置不同

為了更安全,請使用以下API:

Object.getOwnPropertyNames

Object.getOwnPropertyNames(Array.prototype).filter(v=>v.endsWith('custommethod'));//["custommethod", "anothercustommethod"]

如果有符號,您仍然需要

Object.getOwnPropertySymbols(Array.prototype);//[Symbol(Symbol.iterator), Symbol(Symbol.unscopables)]

Object.keys的作用類似於for,它們不會遍歷可枚舉為false的屬性;

當您嘗試使用其他API遍歷屬性時,應考慮這些事情

暫無
暫無

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

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