So what about Javascript, how is it possible to create base class in Javascript?
The tutorial below will show a general example of creating a base class in Javascript
Step 1: First step after creating the javascript file (eg. companyinfo.js), is to first add the following code below, which will will call it, "company_styles":
var company_styles = function(spec){
var that = {};
return that;
}
Step 2: next we have to create a variable function. Here we called a variable function called "CompanyName":
var company_styles = function(spec){
var that = {};
var CompanyName = function(){
return "My Company";
}
return that;
}
Step 3: next we have reference "CompanyName" function to the public function:
var company_styles = function(spec){
var that = {};
var CompanyName = function(){
return "My Company";
}
that.company_name = function(){
return spec.CompanyName || CompanyName();
}
return that;
}
Step 4: Now we would create a new variable for debugging purpose called, "debug_company_styles", which would create a new instance of "company_styles":
var company_styles = function(spec){
var that = {};
var CompanyName = function(){
return "My Company";
}
that.company_name = function(){
return spec.CompanyName || CompanyName();
}
return that;
}
var debug_company_styles = new company_styles({});
Now in Google Chrome, we can debug function called, "company_name", and we can see that the value "My Company" is returned:
Step 5: Next we will see create a new function called, "my_company_styles" just below "company_styles", which will override the function name, "company_name" as shown below. And also, "debug_company_styles" will not create an instance of "my_company_styles":
var company_styles = function(spec){
var that = {};
var CompanyName = function(){
return "My Company";
}
that.company_name = function(){
return spec.CompanyName || CompanyName();
}
return that;
}
var my_company_styles = function(spec){
var that = new company_styles({});
that.company_name = function(){
return "My Other Company";
}
return that;
}
var debug_company_styles = new my_company_styles({});
Now in Google Chrome if we debug again, and called the function, "company_name", we can see that the value "My Other Company" is now returned:
No comments:
Post a Comment