Reputation: 6338
Here: http://www.phpied.com/3-ways-to-define-a-javascript-class/ are described 3 ways to define a "class" in javascript. I chose in my code to use the 3rd method:
var apple = new function(){
//code here
}
I use this construction as a way to separate code in namespaces, I mean I have more variable as apple in the same js file, and each one may contain functions with the same name.
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
}
Now, I noticed that sometimes this.URL is undefined. The this.prepareForm() function exists, is deffined and runs on context, the variable doesn't exist and I need to call it customer.URL instead. But this is only sometimes, not all the time, and I didn't understand why and when happened.
Any suggestion? Why this happens?
Upvotes: 0
Views: 1112
Reputation: 12961
You have some syntax errors in your code and as @Pointy has pointed out, the article is really old-fashioned. I really think you have to change the way you create Javascript classes, you better use prototype to define your class methods, this is ,IMHO, the better way to do what you want:
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
being undefined, this problem happens only if you call the function with a different context, it even can be passing it as a callback or handler, based on your codes I guess you are passing the getData
function as an callback to a ajax call, if it is so you better create an anonymous function and call the customer.getData()
in it.Upvotes: 1
Reputation: 8485
this.json
and this.josn = requestData(this.URL)
are different. cannot be the answer but surely is not the same variable. take a look.
this.json = {};
this.getData = function(id){
this.prepareForm();
this.josn = requestData(this.URL); //requestData deffined in another place
Upvotes: 0