2

I wrote a small hash change object, it will alert the url hash whenever it changes:

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

But this:

this.uponHashChange(hash);

Never gets executed. Why?

asked Oct 4, 2012 at 19:13
1
  • 3
    checkHashChange will run in the context of the global object. You need something like Function.bind. Commented Oct 4, 2012 at 19:16

1 Answer 1

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

This line is not going to do exactly what you mean. this.checkHashChange will lose its binding to its current this (which would be a hashChange instance), and will instead be invoked in the context of the window object.

You need to bind it explicitly to the correct context object:

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

Matt Greer has suggested Function.bind, which would make it more concise and likely more readable:

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

Unfortunately, Function.bind is not yet widely supported across browsers.

answered Oct 4, 2012 at 19:18
Sign up to request clarification or add additional context in comments.

3 Comments

ok but none of this changes the issue with that non executing method: TypeError: this.uponHashChange is not a function, same error even if I store this inside a variable and reference it that way: TypeError: self.uponHashChange is not a function
Please post your updated code, I have no way to know how you have altered your code, considering I haven't advised you to change your uponHashChange invocation at all.
wait never mind, it works now. The bind method wasn't working but the 1st suggestion works. The bind method was giving the uponHashChange error.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.