0

我正在尝试从 Javascript 构造函数内部调用一个方法。这是一个例子:

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

另外:http: //jsfiddle.net/N8Rxt/2/

这行不通。永远不会显示警报。有任何想法吗?谢谢。

4

2 回答 2

4

您需要在定义下方调用 init() 方法。

也可以使用 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);
于 2013-10-07T16:01:28.023 回答
1

预先调用init()withthis并将其移动到对象的末尾有助于:

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/

于 2013-10-07T16:02:01.527 回答