【问题标题】:Extending Object is breaking my code. What can I do?扩展对象正在破坏我的代码。我能做些什么?
【发布时间】:2016-01-01 03:36:15
【问题描述】:

所以我写了一个辅助函数

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 个不同的地方来更改它。

【问题讨论】:

标签: javascript


【解决方案1】:

我会在您的代码中更改它,使用正则表达式并查找和替换您可以相当轻松地完成大部分工作。这就是为什么您不应该修改本机对象,尤其是所有其他继承功能的 Object,这意味着 String.where() Function.where() 等可能会破坏您的代码。

如果您必须修改原生原型,您应该首先检查该方法或属性是否未被添加。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-21
    • 2017-12-04
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    • 2015-10-17
    相关资源
    最近更新 更多