簡體   English   中英

具有擴展原型和“ for-in”循環的JavaScript本機對象

[英]JavaScript native objects with extended prototype and “for-in” loop

我擴展了Array原型:

if(typeof Array.prototype.filter === 'undefined') Array.prototype.filter = function(fun /*, thisp*/){
  var len = this.length;
  if(typeof fun != "function") throw new TypeError();

  var res = [], thisp = arguments[1];

  for(var i=0;i<len;i++){
    if(i in this){
      var val = this[i]; // in case fun mutates this
      if(fun.call(thisp, val, i, this)) res.push(val);
    }
  }

  return res;
};

例如,我創建了數組:

var A = [ 1, 2, 3, 4, 5 ];

然后,我向其中添加了額外的屬性:

A.creator = 'Rustam';
A.created = new Date();

如果我將使用for-in循環,並且瀏覽器沒有對Array.filter內置支持,它將通過A.filter

我這樣知道:

for(var p in A) {
  if (!A.hasOwnProperty(p)) continue
  console.log(p)
};

有沒有辦法for-in不使用hasOwnProperty情況下將A.filter隱藏在for-in


更新回答。 瀏覽器支持:

  • IE9 +
  • FF4 +
  • Opera 11.6+
  • Safari 5+

要定義不會循環顯示的屬性,請使用Object.defineProperty

Object.defineProperty(Array.prototype, 'filter', {value:'XYZ'});

這將Array.prototype擴展為具有默認屬性描述符(包括enumerable: false名為filter屬性,這將導致該屬性不會出現在for( .. in ..)循環中。

參考

PS:在較舊的瀏覽器上將無法使用,我沒有此API的瀏覽器兼容性列表。

暫無
暫無

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

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