簡體   English   中英

從Javascript構造函數內部調用方法

[英]Calling method from inside Javascript constructor

我正在嘗試從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/

這行不通。 該警報從不顯示。 有任何想法嗎? 謝謝。

您需要在定義的下方放置對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);

前面加上調用init()this ,它移動到末尾的對象幫助:

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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM