我正在尝试创建一个封装我们所有javascript类的命名空间,但是在 POI.prototype.getFullAddress 和 >行(POI后停止)。第二个问题是当我尝试初始化对象 var x = new Makani.POI(a,b,c ...)我得到javascript错误并且必须使用 var x = Makani没有新关键字的.POI(a,b,c ...)很奇怪。我发布了完整的代码供参考。谢谢你的帮助。
/* Makani Javascript Libraries */
var Makani = function () {
var private_var;
function private_method() {
// do stuff here
}
return {
POI: function(ID, Title, Section, District, City, Governorate) {
this.ID = ID;
this.Title = Title;
this.Section = Section;
this.City = City;
this.Goverorate = Governorate;
},
POI.prototype.getFullAddress = function (opts) {
if (("includeCity" in opts) && (opts["includeCity"] == false))
return this.Section + ", " + this.District;
else if (("includeGovernorate" in opts) && (opts["includeGovernorate"] == false))
return this.Section + ", " + this.District + ", " + this.City;
else return this.Section + ", " + this.District + ", " + this.City + ", " + this.Governorate;
}
};
} ();
答案 0 :(得分:0)
可能你只想要这个:
POI.getFullAddress: function (opts) {
看起来您正在尝试更改原型,但是您正在该特定块中创建对象定义。另一种方法是将return
部分创建为var,然后扩展原型,然后返回它。
你在简单的层面上做的是:
x = {
name1: value,
name2 = value
}
这是无效的语法。
答案 1 :(得分:0)
JS中的object initialiser(对象文字)如下所示:
{
propName: 123,
123: 'some value',
hmmAFunction: function(){}
}
通常情况下,每个键/值对用逗号分隔PropertyName : AssignmentExpression
。所以,当你这样做时:
return {
POI: function(ID, Title, Section, District, City, Governorate) {
},
// THIS
POI.prototype.getFullAddress = function (opts) {
}
};
...它无效,会导致错误抛出。
请改为尝试:
var Makani = {
POI: (function(){
function POI (ID, Title, Section, District, City, Governorate) {
this.ID = ID;
this.Title = Title;
this.Section = Section;
this.City = City;
this.Goverorate = Governorate;
}
POI.prototype.getFullAddress = function (opts) {
if (("includeCity" in opts) && (opts["includeCity"] == false))
return this.Section + ", " + this.District;
else if (("includeGovernorate" in opts) && (opts["includeGovernorate"] == false))
return this.Section + ", " + this.District + ", " + this.City;
else return this.Section + ", " + this.District + ", " + this.City + ", " + this.Governorate;
};
return POI;
}())
};
另外,我建议不要使用大写字母(例如District
)来启动变量名称,除非它引用的是构造函数(如POI
)。