2013-11-25 92 views
0

我需要新的對象方法。而我試圖創建它:Javascript對象原型錯誤

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文件!):

(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 
    } 
}()); 

Uncaught TypeError: Object function (path, other) {

另一個js文件與該行啓動

我該如何解決這個錯誤?

+0

您可以發佈演示來重現問題嗎? – elclanrs

+3

你確定要添加到'Object'原型嗎?這會將'getByPath'方法添加到**所有**對象 – jasonscript

+0

是的,不建議(或者甚至是有效的)這樣做。 – m59

回答

2

Conflict with another js file!

是的,這是因爲它是添加新的方法把所有的對象,而是儘量讓自己的基本對象爲所有的客戶端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 
+1

+1,但也因爲「其他庫」在使用for..in時沒有采取預防措施防止繼承屬性。 – RobG