如何为Array.prototype添加不可枚举方法以避免影响for...in循环?
如何给Array.prototype添加不可枚举的方法?
你想要为Array.prototype添加方法,但不希望该方法被for...in循环枚举到,避免干扰第三方库的逻辑,同时无法修改第三方库代码来添加hasOwnProperty检测。无论这种做法是否属于最佳实践,确实可以将方法设置为不可枚举。
原问题示例代码
//... Example: //... Only push the value if it is not false Array.prototype.pushValue = function(value){ if(value){ this.push(value); } } var pieces = []; pieces.pushValue(0); pieces.pushValue(1); pieces.pushValue(2); pieces.pushValue(null); console.log(pieces.join(",")); //outputs 1,2 for(var k in pieces){ console.log(k); //outputs 0,1 and pushValue }
解决方案:使用Object.defineProperty()
通过Object.defineProperty()可以精确控制属性(包括方法)的枚举性等特性,将方法设置为不可枚举。修改后的代码如下:
// 定义不可枚举的pushValue方法 Object.defineProperty(Array.prototype, 'pushValue', { value: function(value) { if (value) { this.push(value); } }, enumerable: false, // 设置为不可枚举 writable: true, // 允许方法被重写 configurable: true // 允许方法被删除或重新配置 }); var pieces = []; pieces.pushValue(0); pieces.pushValue(1); pieces.pushValue(2); pieces.pushValue(null); console.log(pieces.join(",")); // 输出 1,2 for(var k in pieces){ console.log(k); // 仅输出 0,1,不会出现pushValue }
关键说明
enumerable: false是核心配置,它会让该方法不会出现在for...in循环的枚举结果中,也不会被Object.keys()等方法获取到。- 额外设置
writable: true和configurable: true是为了让自定义方法和原生数组方法(比如push、forEach)的行为保持一致,允许后续根据需求修改或删除该方法。
内容的提问来源于stack exchange,提问作者Wolfgang Amadeus
相关产品推荐
相关产品推荐

