0

JavaScript でオブジェクトを使用するのは初めてです。このチュートリアルのメソッド 1.1 を使用しました。次のコードがあります。

function MyClass() {
    this.currentTime = 0;

    this.start = function() {
        this.currentTime = new Date().getTime();
        console.log(this.currentTime); //this line prints the time i just set
        this.intervalID = setInterval(this.step, 25);
    };
    this.step = function() {
        var d = new Date().getTime();
        console.log(this.currentTime); //always prints "undefined" to the console
    };

    this.stop = function() {
        clearInterval(this.intervalID);
    };
}    

問題は、step()関数で設定されているconsole.log(this.currentTime)間、常に「未定義」と出力されることです。this.currentTimestart()

なんで?私は何が欠けていますか?

4

1 に答える 1

2

それぞれの場合で関数のスコープを使用してthis.fnいるため、のスコープに追加していませんMyClass。オブジェクトを保存し、thisそれを使用してプロパティを追加する必要があります。

function MyClass() {
    this.currentTime = 0;
    var self = this;
    this.start = function() {
        self.currentTime = new Date().getTime();
        console.log(self.currentTime); //this line prints the time i just set
        self.intervalID = setInterval(self.step, 25);
    };
    this.step = function() {
        var d = new Date().getTime();
        console.log(self.currentTime); //always prints "undefined" to the console
    };

    this.stop = function() {
        clearInterval(self.intervalID);
    };
}
于 2013-06-15T10:35:51.853 に答える