2

小さなハッシュ変更オブジェクトを作成しました。変更されるたびに URL ハッシュに警告します。

(function() {

    function hashChange() {
        this.previousHash;
        this.initialize();
    }

    hashChange.prototype.initialize = function() {
        this.setInterval = window.setInterval(this.checkHashChange, 0);
    }

    hasChange.prototype.uponHashChange = function(hash) {
        alert('I executed!');
        var hashValue = hash.split('#')[1];
        alert(hashValue);
    }

    hashChange.prototype.checkHashChange = function() {
        var hash = window.location.hash;
        if(hash && hash !== this.previousHash) {
            this.previousHash = hash;
            this.uponHashChange(hash); // <---- doesn't execute
        }
    }

    var hashChange = new hashChange();

})();

でもこれは:

this.uponHashChange(hash);

実行されることはありません。なんで?

4

1 に答える 1

5
this.setInterval = window.setInterval(this.checkHashChange, 0);

この行は、あなたが言っていることを正確に行うつもりはありません。現在の(インスタンスになる)this.checkHashChangeへのバインディングが失われ、代わりにオブジェクトのコンテキストで呼び出されます。thishashChangewindow

正しいコンテキスト オブジェクトに明示的にバインドする必要があります。

var self = this;
this.setInterval = window.setInterval(function() { self.checkHashChange() }, 0);

Matt Greer は を提案してFunction.bindいます。これにより、より簡潔になり、読みやすくなります。

this.setInterval = window.setInterval(checkHashChange.bind(this), 0);

残念ながら、Function.bindブラウザ間でまだ広くサポートされていません。

于 2012-10-04T19:18:43.263 に答える