Javascript对象原型错误

时间:2013-11-25 06:08:00

标签: javascript object prototype

我需要对象的新方法。我试图创建它:

Object.prototype.getByPath = function (path, other) {
    for (var i=0, obj=this, path = path.split('.'), len=path.length; i<len; i++) {
        obj = obj[path[i]];
    }
    return (typeof obj === "undefined" || obj == "") ? other : obj;
}

但是这段代码会返回一个错误(与另一个js文件冲突!):

  

未捕获的TypeError:对象函数(路径,其他){

另一个js文件以此行开头:

(function(){function d(a,b){
    try {
      for (var c in b)
        Object.defineProperty(a.prototype, c, {value:b[c],enumerable:!1})
    } catch(d) {
      a.prototype = b
    }
}());

如何解决此错误?

1 个答案:

答案 0 :(得分:2)

  

与另一个js文件发生冲突!

是的,因为它正在向所有对象添加新方法,而是尝试为所有客户端javascript对象创建自己的基础对象,

var yourBaseObj={
  getByPath :function (path, other) {
    for (var i=0, obj=this, path = path.split('.'), len=path.length; i<len; i++) {
        obj = obj[path[i]];
    }
    return (typeof obj === "undefined" || obj == "") ? other : obj;
  }
}

然后将它用于其他对象,

function YourNewObject(){

}
YourNewObject.prototype=yourBaseObj