[英]Javascript object prototype error
I need new method for the object. 我需要对象的新方法。 And I'm trying to create it:
而我正在尝试创建它:
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;
}
But this code return an error (Conflict with another js file!): 但是这段代码返回一个错误(与另一个js文件冲突!):
Uncaught TypeError: Object function (path, other) {
未捕获的TypeError:对象函数(路径,其他){
Another js file start with this line: 另一个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
}
}());
How can I solve this error? 我该如何解决这个错误?
Conflict with another js file!
与另一个js文件冲突!
Yes it happens because it is adding the new method to all the objects , Instead try to make your own base object for all your clients side javascript objects, 是的,因为它正在向所有对象添加新方法,而是尝试为所有客户端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;
}
}
And then you it for other objects , 然后你把它用于其他物体,
function YourNewObject(){
}
YourNewObject.prototype=yourBaseObj
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.