0

I'm trying to call a method from inside a Javascript contructor. Here's an example:

function team(team_id) {
    this.team_id = team_id;
    init();

    this.init = function () {
        alert('testing this out: ' + this.team_id);
    };
}

var my_team = new team(15);

Also: http://jsfiddle.net/N8Rxt/2/

This doesn't work. The alert is never displayed. Any ideas? Thanks.

2 Answers 2

4

You need to place your call to the init() method, underneath the definition.

Also call it using this.init();

function team(team_id) {
    this.team_id = team_id;

    this.init = function () {
        alert('testing this out: ' + this.team_id);
    };

    this.init();
}

var my_team = new team(15);
Sign up to request clarification or add additional context in comments.

Comments

1

Prepending the call to init() with this and moving it to the end of the object helps:

function team(team_id) {
    this.team_id = team_id;

    this.init = function () {
        alert('testing this out: ' + this.team_id);
    };

    this.init();
}

var my_team = new team(15);

http://jsfiddle.net/N8Rxt/3/

Comments

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.