扩展对象正在破坏我的代码.我能做什么

Extending Object is breaking my code. What can I do?

本文关键字:代码 什么 我的 对象 扩展      更新时间:2023-09-26

所以我写了一个辅助函数

Object.prototype.Where = function ( boofunc ) {
  // Returns an object whose own properties are  
  // those properties p of this object that satisify
  // the condition boofunc(p)
    var that = new Object();
    for ( var prop in this )
    {
        if ( this.hasOwnProperty(prop) && boofunc(this[prop]) )
        that[prop] = this[prop];
    }
    return that;
}

我已经确定这会破坏我的代码,因为它会给我带来错误,比如

对象不支持属性或方法"exec"

在我包含的其他JavaScript文件中。问题是我已经用了100次这个函数了。。。所以我想知道是否有任何方法可以改变身体来解决问题。如果我必须去掉这个功能,把它改成之类的东西

function Where ( obj, boofunc ) 
{
        var newobj = new Object();
        for ( var prop in obj )
        {
            if ( obj.hasOwnProperty(prop) && boofunc(obj[prop]) )
            newobj[prop] = obj[prop];
        }
        return newobj;
}

然后我必须遍历代码中的100个不同位置才能更改它。

我会在你的代码中更改它,使用regex并查找和替换,你可以很容易地完成大部分工作。这就是为什么你不应该修改本机对象,尤其是其他所有功能都继承自的Object。这意味着String.where()Function.where等可能会破坏你的代码。

此外,如果必须修改本机原型,则应首先检查该方法或属性是否尚未添加。

if( typeof Object.prototype.where === 'undefined' ){
  Object.prototype.where = function where(){ ... }
}