为什么赢了';这不是JavaScript函数的火吗?

为什么赢了';这不是JavaScript函数的火吗?,javascript,Javascript,我编写了一个小的hash change对象,它会在url hash发生更改时发出警报: (function() { function hashChange() { this.previousHash; this.initialize(); } hashChange.prototype.initialize = function() { this.setInterval = window.setInterval(this.

我编写了一个小的hash change对象,它会在url hash发生更改时发出警报:

(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.setInterval = window.setInterval(this.checkHashChange, 0);
这句话不会完全符合你的意思
this.checkHashChange
将失去与当前
this
(这将是
hashChange
实例)的绑定,并将在
窗口
对象的上下文中调用

您需要将其显式绑定到正确的上下文对象:

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
尚未在浏览器中得到广泛支持。

checkHashChange将在全局对象的上下文中运行。您需要类似Function.bind.ok的东西,但这些都不能改变非执行方法的问题:
TypeError:this.uponHashChange不是函数
,即使我将其存储在变量中并以这种方式引用它,也会出现相同的错误:
TypeError:self.uponHashChange不是函数
,请发布更新的代码,考虑到我根本没有建议您更改
uponHashChange
调用,我无法知道您是如何更改代码的。等等,没关系,它现在可以工作了。bind方法不起作用,但第一个建议起作用。bind方法给出了uponHashChange错误。
this.setInterval = window.setInterval(checkHashChange.bind(this), 0);