I am trying to use something similar to Objects/Classes in JavaScript. I found out that this can be done via a function. So my class code is like this: (using jQuery)
function InfoBox(Box) { // My class
this.Box = Box; // html element
this.Text = 'Information here';
this.Image = 'foo.png';
setText = function () {
this.Box.children('.Text').html(this.Text);
}
}
The variables in the function work fine but whenever I call the method/function "setText" via
var iBoxUser = new InfoBox($('.iBoxUser'));
iBoxUser.Text = 'Welcome';
iBoxUser.setText(); // Error occurs here
I get the error: "Uncaught TypeError: undefined is not a function"
It seems that I'm somehow doing the function thing wrong. Or can functions even contain other functions?
2 Answers 2
Change
setText = function () {
To:
this.setText = function () {
Update: As comments say, you could also set the function outside your Infobox:
InfoBox.prototype.setText = function () {
3 Comments
setText outside the function, and write InfoBox.prototype.setText =You are experiencing a scope problem, what you are doing here is that you set the global variable setText to a function expression (it may or may not exist at the moment you declare it). This kind of errors can be avoided by setting strict mode.
To expose setText as a method I suggest you to attach it to the prototype of InfoBox
function InfoBox(Box) { // My class
this.Box = Box; // html element
this.Text = 'Information here';
this.Image = 'foo.png';
}
InfoBox.prototype.setText = function () {
this.Box.children('.Text').html(this.Text);
}