You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何添加可写的Object.prototype.forEach方法以避免与RxJS冲突?

如何为Object.prototype添加可写的forEach方法?

我想给Object原型扩展forEach方法,按照相关指南实现后,却导致其他代码(比如RxJS)报错:Error: adding forEach in object prototype makes it readonly,同时其他自定义的forEach原型代码也失效了。请问有没有办法在添加Object.prototype.forEach的同时保留它的可写性?

当前实现代码:

if (!Object.prototype.forEach) {
    Object.defineProperty(Object.prototype, 'forEach', {
        value: function (callback, thisArg) {
            if (this == null) {
                throw new TypeError('Not an object');
            }
            thisArg = thisArg || window;
            for (var key in this) {
                if (this.hasOwnProperty(key)) {
                    callback.call(thisArg, this[key], key, this);
                }
            }
        }
    });
}

解决方案

问题出在Object.defineProperty的默认配置上:它会把新增属性默认设为不可写(writable: false)、不可配置(configurable: false)。要让forEach方法保持可写,只需在配置对象里显式声明writable: true和configurable: true即可。

修改后的代码:

if (!Object.prototype.forEach) {
    Object.defineProperty(Object.prototype, 'forEach', {
        value: function (callback, thisArg) {
            if (this == null) {
                throw new TypeError('Not an object');
            }
            thisArg = thisArg || window;
            for (var key in this) {
                if (this.hasOwnProperty(key)) {
                    callback.call(thisArg, this[key], key, this);
                }
            }
        },
        writable: true, // 显式设置为可写
        configurable: true, // 允许后续修改或删除该属性
        enumerable: false // 保持不可枚举,避免遍历对象时被误当成普通属性
    });
}

额外说明

  • 加上enumerable: false是必要的,这能让for...in遍历对象时不会把forEach方法列出来,和数组forEach的行为保持一致。
  • 显式开启writable和configurable,就能让其他代码有机会修改这个方法,避免与RxJS这类库的逻辑冲突。

内容的提问来源于stack exchange,提问作者OtaconKiko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 23:33:19