此处:http://www.phpied.com/3-ways-to-define-a-javascript-class/描述了在javascript中定义“类”的3种方法。我在我的代码中选择使用第三种方法:
var apple = new function(){
//code here
}
我使用这种结构作为分隔命名空间中代码的方法,我的意思是我在同一个js文件中有更多变量 apple ,并且每个变量可能包含具有相同名称的函数。
var customer = new function(){
this.URL = "//customer/";
this.json = {};
this.getData = function(id){
this.prepareForm();
this.json = requestData(this.URL); //requestData deffined in another place
}
this.save = function(){
//code
}
this.validate = function(){
//code
}
this.prepareForm = function(){
//code
}
// more code here
}
var employee = new function(){
//code here, something like the customer code
}
var partner = new function(){
//code here, something like the customer code
}
现在,我注意到有时 this.URL 未定义。存在 this.prepareForm()函数,并在上下文中运行,该变量不存在,我需要将其称为customer.URL。但这只是有时,而不是所有时间,我不明白为什么以及何时发生。
有什么建议吗?为什么会这样?
答案 0 :(得分:1)
你的代码中有一些语法错误,正如@Pointy指出的那样,这篇文章真的很老套。我真的认为你必须改变你创建Javascript类的方式,你最好用prototype来定义你的类方法,这就是恕我直言,更好的方法来做你想做的事情:
var Customer = function Customer(){
this.URL = "//customer/";
this.json = {};
};
Customer.prototype.getData = function(id){
this.prepareForm();
this.josn = requestData(this.URL);
};
Customer.prototype.save = function()(){
//code
};
Customer.prototype.validate = function()(){
//code
};
Customer.prototype.prepareForm = function()(){
//code
};
var customer = new Customer();
//you can here call your methods like:
customer.validate();
this.URL
未定义的具体问题,只有当您使用不同的上下文调用该函数时才会出现此问题,它甚至可以将其作为回调或处理程序传递,根据你的代码,我猜你传递getData
函数作为ajax调用的回调,如果是这样你最好创建一个匿名函数并调用其中的customer.getData()
。答案 1 :(得分:0)
this.json
和this.josn = requestData(this.URL)
不同。不可能是答案,但肯定不是同一个变量。看一看。
this.json = {};
this.getData = function(id){
this.prepareForm();
this.josn = requestData(this.URL); //requestData deffined in another place