Reputation: 701
This is my Javascript code
Html5Template_300x250 = function(config) {
this.config = config;
var self = this;
this.init();
Html5Template_300x250.prototype = {
// Function That Creates Element Var
d: function(id) {
return document.getElementById(id);
},
// Initialize DCO HTML5 template
init: function() {
alert("test1");
this.startAd();
},
startAd: function() {
alert("test2");
}
};
}
From the HTML file i am creating method like this
var sr_Config = {
bgColor:'#fff',
ctaText:'Learn More',
border: 'true'
};
var Html5Template = new Html5Template_300x250(sr_Config);
But i am getting Error
TypeError: this.init is not a function this.init();
I am not sure what is wrong here i have also tried self.init() but still it is not working.
I am new to javascript and learning OOPS in Javascript if anyone can tell me what i am doing wrong here that would be great. Thanks in advance
Upvotes: 3
Views: 16768
Reputation: 9659
You need to assing the methods to the prototypes properties (at least thats how i do it). You also need to do so before you call the function (above).
Html5Template_300x250 = function(config) {
this.config = config;
var self = this;
Html5Template_300x250.prototype.d = function(id) {
return document.getElementById(id);
};
Html5Template_300x250.prototype.startAd = function() {
alert("test2");
};
// Initialize DCO HTML5 template
Html5Template_300x250.prototype.init = function() {
alert("test1");
this.startAd();
};
self.init();
}
Another way to do this w/o the prototype
-stuff would be sth. like that:
Html5Template_300x250 = function(config) {
this.config = config;
var self = this;
this.d = function(id) {
return document.getElementById(id);
};
// and so on..
self.d('myid');
}
See this working fiddle with some sample code.
Further interesting reading on the topic OOP in JS is provided by JS-Guru Douglas Crocford ;)
Upvotes: 3