[英]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
?
更新回答。 瀏覽器支持:
要定義不會循環顯示的屬性,請使用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.