javascript";“类”;变量未定义
这里:描述了用javascript定义“类”的3种方法。我在代码中选择使用第三种方法:javascript";“类”;变量未定义,javascript,Javascript,这里:描述了用javascript定义“类”的3种方法。我在代码中选择使用第三种方法: var apple = new function(){ //code here } 我使用这种结构来分离名称空间中的代码,我的意思是在同一个js文件中有更多变量,如apple,并且每个变量可能包含具有相同名称的函数 var customer = new function(){ this.URL = "//customer/"; this.json = {}; this.get
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。但这只是有时候,不是所有的时候,我不明白为什么和什么时候发生的
有什么建议吗?为什么会发生这种情况?
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
您的代码中有一些语法错误,正如@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
函数作为对ajax调用的回调传递,如果是这样,您最好创建一个匿名函数并调用其中的getData
customer.getData()
this.validate(){
看起来不对?您的意思是this.validate=function(){
?还要注意的是,根据JavaScript最佳实践标准,这篇博客文章确实很旧。编辑。我直接在stackoverflow上写了cod,但我没有看到我没有很好地定义函数。重点是函数是可以的,我的问题是URL变量,有时它是未定义的,我不明白为什么!Pointy:你有吗e有没有关于这方面的新文章的建议?为什么没有?我不理解它拼写错误,一个是this.json,另一个是this.josnj,这是一个speling错误,因为我直接在浏览器窗口上编写了所有代码。真正的代码是正确的,但有时该变量还没有定义