0

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

6

Change

setText = function () {

To:

this.setText = function () {

Update: As comments say, you could also set the function outside your Infobox:

InfoBox.prototype.setText = function () {
Sign up to request clarification or add additional context in comments.

3 Comments

Better yet, move setText outside the function, and write InfoBox.prototype.setText =
I am so stupid. Can you beleve that I was searching for the error for 3 days now? You saved my day! Thank you a lot!
@user2334932 happens to the best of us! Next time try to ask for help after just 1 day ;)
1

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);
}

1 Comment

ok thank you. I've seen this prototype already but thought its a member of the function. Now I see that this is an internal member of every JS object. thx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.